std :: thread.join()有什么作用?

Gua*_*gua 30 c++ multithreading mutex

根据C++参考定义:

阻塞当前线程,直到标识的线程*this完成其执行.

这是否意味着在使用时.join(),没有必要mutex.lock()在该线程调用某些函数时?我是新的互斥和线程,所以我有点困惑.

注意:我找到了一本书C++ Concurrency in Action,我正在读这本书.这对于像我这样的多线程初学者来说非常好.

谢谢大家的帮助.

Joe*_*oel 22

你仍然需要互斥和条件.加入一个线程使一个执行线程等待另一个线程完成运行.您仍需要互斥锁来保护共享资源.它允许此示例中的main()在退出之前等待所有线程完成.

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

using namespace std;



int global_counter = 0;
std::mutex counter_mutex;

void five_thread_fn(){
    for(int i = 0; i<5; i++){
        counter_mutex.lock();
        global_counter++;
        counter_mutex.unlock();
        std::cout << "Updated from five_thread"  << endl;
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
    //When this thread finishes we wait for it to join
}

void ten_thread_fn(){
    for(int i = 0; i<10; i++){
        counter_mutex.lock();
        global_counter++;
        counter_mutex.unlock();
        std::cout << "Updated from ten_thread"  << endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    //When this thread finishes we wait for it to join
}
int main(int argc, char *argv[]) {
    std::cout << "starting thread ten..." << std::endl;
    std::thread ten_thread(ten_thread_fn);

    std::cout << "Running ten thread" << endl;
    std::thread five_thread(five_thread_fn);


    ten_thread.join();
    std::cout << "Ten Thread is done." << std::endl;
    five_thread.join();
    std::cout << "Five Thread is done." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

请注意,输出可能如下所示:

starting thread ten...
Running ten thread
Updated frUopmd atteend_ tfhrroema df
ive_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from five_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from five_thread
Ten Thread is done.
Updated from five_thread
Updated from five_thread
Five Thread is done.
Run Code Online (Sandbox Code Playgroud)

由于std :: cout是一个共享资源访问,因此它的使用也应该是互斥保护.

  • 谢谢 Joel,所以这里 ten_thread.join() 会告诉程序 ten_thread 已完成,并且可以进入下一步? (2认同)
  • 运行main()的执行线程将在调用ten_thread.join()时阻塞,直到ten_thread返回.一旦ten_thread执行结束,main的执行就被允许继续.希望这可以帮助. (2认同)

小智 9

join()停止当前线程,直到另一个完成.互斥锁会停止当前线程,直到互斥锁所有者释放它为止,如果未锁定,则立即锁定.所以这些家伙是完全不同的

  • 不过,我更喜欢"暂停"而不是"停止". (10认同)

小智 7

它阻塞当前线程,直到调用 join() 的线程执行完成。

如果您没有在线程上指定 join() 或 dettach() ,那么它将导致运行时错误,因为主/当前线程将完成其执行而创建的另一个线程将仍在运行。