我们的老师在课堂上向我们介绍了这个代码
他声称对于给定的随机线程ids(例如主线程9443200' hello'线程9454310和' world'线程9454388)
输出可能
" 1。世界 - 9454388"
将在第一次时间之前打印输出
"线程ID:9443200"
印刷品
在我看来,这是不可能的,因为主线是派遣世界的主要线索。线程,但它也是调度hello线程的那个,它(主线程)打印出"线程id:9443200"消息,因此在没有上下文切换的情况下,可以获得他提到的打印顺序。
template<class Function>
class Runner {
Function func;
std::unique_ptr<std::mutex> m = std::make_unique<std::mutex>();
public:
Runner(Function f): func(f) {}
// runInNewThread creates a new thread and calls func in a loop
template<typename... Params>
std::thread runInNewThread(int times, Params&&... params) {
std::thread t(
[times, ¶ms..., this]() {
auto t_id = std::this_thread::get_id();
for(int i=1; i<=times; ++i) {
std::lock_guard<std::mutex> lock(*m);
func(i, std::forward<Params>(params)...);
cout << " - " << t_id << endl;
}
cout << t_id << " finished the loop!" << endl;
});
cout << "thread id: " << std::this_thread::get_id() << endl;
return t;
}
};
template<class Function>
Runner<Function> createRunner(Function f) {
return f;
}
int main() {
auto runner = createRunner (
[](int i, auto obj) {
cout << i << ". " << obj;
}
);
auto t1 = runner.runInNewThread(3, "hello");
auto t2 = runner.runInNewThread(3, "world");
t1.join();
t2.join();
}
我是否错过了上下文切换和cpp中的线程的内容? 谢谢!