C++;11线程简单示例 我是C++新手,我正在看一些C++跨平台线程教程。我在调查这件事:
并试图执行以下代码:C++;11线程简单示例 我是C++新手,我正在看一些C++跨平台线程教程。我在调查这件事:,c++,multithreading,c++11,iostream,C++,Multithreading,C++11,Iostream,并试图执行以下代码: #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::e
#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;
}
我知道每次数字都是随机的,但有时我看不到数字,我想知道为什么?它们都在那里。因为控制台输出是以模糊的随机顺序进行的,所以它们被弄乱了
特别是查看第一行输出的末尾。您需要做的就是添加一个互斥锁并将其锁定在正确的位置:
std::mutex mtx;
-
void从线程调用线程(inttid){
mtx.lock();
-----------------------------------------------------------
标准::cout冲洗流应起作用:)
下一行:std::cout中的IO(cout)中存在竞争条件
创建线程时,将在创建时调用函数call\u from\u thread
所以最好是搬家
std::cout << "Launched from the main\n";
<代码> STD::CUT没有逐行或<代码>操作器更精确,C++标准指定了[IoSoSo.Objist.Orthy]/4中的标准流。“多线程对同步标准iostream对象的格式化和未格式化输入输出函数或标准C流的并发访问不应导致数据竞争。[注:如果用户希望避免交错字符,则必须同步多线程对这些对象和流的并发使用。-结束注]“类似于std::string str=“由线程启动”然后是str.append(tid)然后打印出来就行了fine@James:并非完全无用,只是有点不方便,迫使您格式化整行(或按您希望的方式组合在一起)如果您不关心类型安全或对用户定义类型的支持,则在流式处理之前将其作为单个字符串。printf
可能更方便。@LanPac:这也不能保证。
void call_from_thread(int tid) {
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched by thread " << tid << std::endl;
-----------------------------------------------------------
mtx.unlock();
}
mtx.lock();
-----------------------------------------------------------
std::cout << "Launched from the main\n";
-----------------------------------------------------------
mtx.unlock();
std::cout << "Launched by thread " << tid << std::endl;
std::cout << "Launched by thread " ;
cout<< tid ;
cout<< std::endl;
void call_from_thread(int tid) {
std::cout << std::string("Launched by thread " + std::to_string(tid) + "\n");
}
t[i] = std::thread(call_from_thread, i);
std::cout << "Launched from the main\n";
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
mutex g_i_mutex; // protects cout
void call_from_thread(int tid) {
lock_guard<mutex> lock(g_i_mutex);
cout << "Launched by thread " ;
cout<< tid ;
cout<< std::endl;
}