gpt4 book ai didi

c++ - std::thread.join() 做什么?

转载 作者:IT老高 更新时间:2023-10-28 12:48:10 26 4
gpt4 key购买 nike

作者 definition from C++ reference :

Blocks the current thread until the thread identified by *this finishes its execution.

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

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

感谢大家的帮助。

最佳答案

您仍然需要互斥锁和条件。加入一个线程使一个执行线程等待另一个线程完成运行。您仍然需要互斥锁来保护共享资源。它允许本例中的 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 是共享资源访问和使用它也应该受到互斥保护。

关于c++ - std::thread.join() 做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com