简体   繁体   English

thread.join()如何工作?

[英]How thread.join() works?

I am having trouble understanding thread.join(); 我无法理解thread.join();

I have surfed the documentations for explanation but of no avail. 我已经浏览了文件以供解释,但没有用。 The following program is a part of our assignment and simulates the Petersons solution using pthreads. 以下程序是我们任务的一部分,并使用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;
 }

The question that I particularly have is: 我特别关注的问题是:

The following line from cppreference for thread.join() thread.join()的cppreference中的以下行

Blocks the current thread until the thread identified by *this finishes its execution. 阻止当前线程,直到* this标识的线程完成其执行。

The completion of the thread identified by *this synchronizes with the corresponding successful return from join(). 由*标识的线程的完成与join()的相应成功返回同步。

Which thread is *this here? 这是哪个线程*? , and how multiple joined threads execute and in what order? ,以及多个连接的线程如何执行以及以什么顺序执行?

It will be quite intuitive if the explanation can be provided with reference to the code. 如果可以参考代码提供解释,那将是非常直观的。

*this is a pointer referring to the actual thread handling the threads you are working on *这是一个指针,指的是处理您正在处理的线程的实际线程

eg if you do 例如,如果你这样做

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

then the thread owning the main function will be blocked until foo is done! 拥有主函数的线程将被阻塞,直到foo完成!

There is already an answer for the first part of your question... for the second part 对于第二部分,您的问题的第一部分已经有了答案

[...] how multiple joined threads execute and in what order? [...]多个连接的线程如何执行以及以什么顺序执行?

Once joined the thread does not execute anymore, because join blocks until the thread finishes its execution. 一旦加入,线程就不再执行,因为join阻塞直到线程完成执行。 If you dont implement dedicated measures, you dont know in what order threads execute and even if you have 如果你没有实现专门的措施,你不知道线程执行的顺序,即使你有

t1.join();
t2.join();

it might be that t2 finishes before t1 , but your program will first wait for t1 to finish and only then for t2 . 可能是t2t1之前完成,但是你的程序将首先等待t1完成,然后才等待t2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM