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

时间:2013-03-01 00:04:03

标签: c++ multithreading mutex

definition from C++ reference

  

阻止当前线程,直到*this标识的线程完成执行。

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

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

谢谢大家的帮助。

4 个答案:

答案 0 :(得分:21)

您仍需要互斥锁和条件。加入一个线程使一个执行线程等待另一个线程完成运行。您仍需要互斥锁来保护共享资源。它允许此示例中的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;
}

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

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.

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

答案 1 :(得分:7)

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

答案 2 :(得分:2)

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

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

答案 3 :(得分:-1)

std :: thread.join有三个我能想到的功能和其他一些功能:

a)鼓励不断创建/终止/销毁线程,从而锤击性能并增加泄漏的可能性,线程失控,内存失控以及应用程序的一般失控。

b)通过强制执行不必要的等待来填充GUI事件处理程序,导致客户不喜欢无响应的“沙漏应用程序”。

c)导致应用程序无法关闭,因为它们正在等待无关的不间断线程的终止。

d)其他坏事。

我知道你是多线程的新手,我希望你能做到最好。另外,考虑到今晚我有很多Adnams Broadside,但是:

加入(),而其他语言的朋友,如TThread.WaitFor,(Delphi),就像Windows ME一样高效的多线程操作系统。

请努力进步并了解其他多线程概念 - 池,任务,应用程序生命周期线程,通过生产者 - 消费者队列的线程间通信。事实上,几乎除Join()之外的任何事情。