C++ 11 线程简单示例
C++ 11 thread simple example
我是 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 mainn";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
我得到的输出如下,我不明白为什么:
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
我知道每次的数字都是随机的,但有时我没有显示任何数字,我想知道为什么?
您
需要做的就是添加一个互斥锁并将其锁定在正确的位置:
std::mutex mtx;
-
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 mainn";
-----------------------------------------------------------
mtx.unlock();
参考这个
他们都在那里。它们只是被破坏了,因为控制台输出以模糊的随机顺序发生。
特别是看看第一行输出的末尾。
IO(cout) 中存在争用条件
std::cout << "Launched by thread " << tid << std::endl;
实际上,没有保证cout("由线程启动",tid,std::endl)排序。它的行为是这样的:
std::cout << "Launched by thread " ;
cout<< tid ;
cout<< std::endl;
您可以将call_from_thread更改为:
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);
创建线程时,将在创建时调用函数call_from_thread。
所以最好搬家
std::cout << "Launched from the mainn";
以前
//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;
}
刷新流应该可以解决问题:)
以下行:std::cout << "Launched by thread " << tid << std::endl;
更改为:std::cout << "Launched by thread " << tid << std::endl << std::flush;
相关文章:
- 简单使用 std::atomic 在两个线程之间共享数据
- 多线程 gtkmm 应用程序最简单的示例
- 对于 ~95% 写入/5% 读取线程安全的无序列图,有没有一个简单的解决方案?
- 一个简单的 win32 多线程代码.这能行吗?
- 简单的C++循环无法从多线程中受益
- 需要帮助识别简单多线程代码中的错误
- 从线程输出简单向量
- 简单的非阻塞多线程 tcp 服务器
- 简单的线程池不会嗡嗡作响
- 为什么我不能编译这个简单的线程测试?
- 简单线程程序的链接器错误(缺少boost_chrono符号)
- 使用 Qt 的简单线程 gui 应用程序的结构是什么?
- C++简单线程示例
- 实现简单线程安全通用互斥锁的正确方法
- C++错误中的简单线程 - 尚未声明'Lib'
- 在c++中创建简单线程时出错
- c++简单线程问题
- Dev c++使用windows.h的简单线程示例
- c++简单线程池
- 我的简单线程安全堆栈有什么问题?