执行中的线程顺序
Order of threads in execution
考虑这个简单的并发示例:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
void print_block(int n, char c) {
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
for (int i = 0; i<n; ++i) { std::cout << c; }
std::cout << 'n';
mtx.unlock();
}
int main()
{
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
是否总是保证th1
将是执行for循环的第一个线程?
意思是,当我这样做的时候:
th1.join();
th2.join();
那么我可以绝对确定th1
将首先执行,然后是th2
吗?
不,您很可能看到th1
总是首先启动,因为该变量的线程构建首先完成(线程构建是昂贵的),因此th2
在之后启动。这并不意味着有一个顺序。
调用join()
与哪个线程首先被执行没有任何关系,这是在构造时提供可调用对象时完成的。
th1
可以被构建,然后被操作系统停止,这将导致th2
首先运行。没有秩序,就没有秩序。
考虑这个例子,它给了两个线程一个更公平的开始,它有时输出线程1作为第一个获得锁,它有时输出线程2。
的例子:
#include <iostream> // std::cout
#include <string> // std::string
#include <unordered_map> // std::unordered_map<K, V>
#include <thread> // std::thread
#include <mutex> // std::mutex
#include <atomic> // std::atomic<T>
std::unordered_map<std::thread::id, std::string> thread_map;
std::mutex mtx; // mutex for critical section
std::atomic<bool> go{ false };
void print_block( int n, char c )
{
while ( !go ) {} // prevent threads from executing until go is set.
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
std::cout << thread_map.find( std::this_thread::get_id() )->second <<
" acquires the lock.n";
mtx.unlock();
}
int main()
{
std::thread th1( print_block, 50, '*' );
std::thread th2( print_block, 50, '$' );
thread_map.emplace( std::make_pair( th1.get_id(), "Thread 1" ) );
thread_map.emplace( std::make_pair( th2.get_id(), "Thread 2" ) );
go.store( true );
th1.join();
th2.join();
return 0;
}
相关文章:
- 如何创建线程序列以按照启动顺序执行任务?
- ASIO signal_set多个 IO 线程不可靠,具体取决于代码顺序?
- 如何使用 OpenMP 使线程以相反的顺序写入其数字?
- 线程局部变量的初始化顺序
- 顺序一致的原子负载(负载-负载对)是否形成线程间同步点
- 多个线程之间的获取-释放内存顺序
- 按顺序保留多线程API的传入请求订单
- 是否有一种可接受的运行线程或按顺序执行的方法
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 联接线程如何影响主线程中的执行顺序?
- 使用多个线程的并行向量乘法比顺序乘法需要更长的时间
- 如何使一个线程按预期顺序多次等待另一个线程
- 具有`k`线程的多线程程序的运行速度都比其顺序版本快
- 我应该为等待工作线程的主线程使用哪种内存顺序
- C++ 多线程:执行顺序
- C 静态与线程存储持续时间破坏顺序
- 以特定顺序运行八个线程,直到终止
- 线程的执行顺序
- XSetWMProtocols 和 glXCreateContext 在多线程环境中调用顺序
- 避免顺序线程中的冲突