执行中的线程顺序



考虑这个简单的并发示例:

#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;
}

最新更新