gpt4 book ai didi

c++ - thread.join() 如何工作?

转载 作者:行者123 更新时间:2023-11-30 02:25:26 28 4
gpt4 key购买 nike

我无法理解 thread.join();

我已经浏览了文档以进行解释,但无济于事。以下程序是我们作业的一部分,使用 pthreads 模拟了 Petersons 的解决方案。

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

using namespace std;

bool flag[2];
char turn;

mutex mux1;
mutex mux2;

void first(int num)
{
flag[0] = true;
turn = 'j';

while ( turn == 'j' && flag[1] == true )
;

mux1.lock();
cout<<" in critical section of i with thread number "<<num<<endl;
mux1.unlock();

flag[0] = false;
}

void second(int num)
{
flag[1] = true;
turn = 'i';

while ( turn == 'i' && flag[0] == true )
;

mux2.lock();
cout<<" in critical section of j with thread number "<<num<<endl;
mux2.unlock();

flag[1] = false;
}

int main()
{
thread k[3];
thread j[3];

for(int i=0;i<3;i++)
j[i] = thread(second,i);

for(int i=0;i<3;i++)
k[i] = thread(first,i);

for(int i=0;i<3;i++)
{
j[i].join();
k[i].join();
}

return 0;
}

我特别有疑问的是:

thread.join() 的 cppreference 中的以下行

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

The completion of the thread identified by *this synchronizes with the corresponding successful return from join().

这里*this 是哪个线程? ,以及多个加入的线程如何执行以及以什么顺序执行?

如果能结合代码给出解释就很直观了。

最佳答案

*这是一个指针,指向处理您正在处理的线程的实际线程

例如如果你这样做

main(){
std::thread foo(x);
foo.join();
}

然后拥有 main 函数的线程将被阻塞,直到 foo 完成!

关于c++ - thread.join() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44134763/

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