My code:
#include <iostream>
#include <thread>
void function_1()
{
std::cout << "Thread t1 started!\n";
for (int j=0; j>-100; j--) {
std::cout << "t1 says: " << j << "\n";
}
}
int main()
{
std::thread t1(function_1); // t1 starts running
for (int i=0; i<100; i++) {
std::cout << "from main: " << i << "\n";
}
t1.join(); // main thread waits for t1 to finish
return 0;
}
我创建一个thread
以降序打印数字,同时main
按递增顺序打印。
样本输出here https://gist.github.com/sivapvarma/0dd6ca186a93e8f30ae7#file-output-txt。为什么我的代码打印垃圾?
两个线程同时输出,从而扰乱你的输出。
打印部分需要某种线程同步机制。
See 这个答案 https://stackoverflow.com/a/18277334/5708620举个例子,使用std::mutex http://en.cppreference.com/w/cpp/thread/mutex结合std::lock_guard http://en.cppreference.com/w/cpp/thread/lock_guard for cout
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)