Sas*_*dar 17 c++ multithreading iostream c++11
我是c ++的新手,我正在研究一些c ++跨平台线程教程.我正在研究这个问题:http://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
并试图执行以下代码:
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出如下,我无法理解为什么:
syd@syd-HP-Compaq-dx7500-Microtower:~/Desktop$ ./ref
Launched by thread Launched by thread Launched by thread Launched by thread Launched by thread 201
Launched by thread 5
Launched by thread 6
4
Launched by thread 7
3
Launched by thread 8
Launched from the main
Launched by thread 9
Run Code Online (Sandbox Code Playgroud)
我知道这些数字每次都是随机的,但有时我没有显示数字,我想知道为什么?
小智 12
您需要做的就是添加一个互斥锁并将其锁定在正确的位置:
std::mutex mtx;
Run Code Online (Sandbox Code Playgroud)
-
void call_from_thread(int tid) {
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched by thread " << tid << std::endl;
-----------------------------------------------------------
mtx.unlock();
}
Run Code Online (Sandbox Code Playgroud)
-
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched from the main\n";
-----------------------------------------------------------
mtx.unlock();
Run Code Online (Sandbox Code Playgroud)