简体   繁体   中英

How thread.join() works?

I am having trouble understanding 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.

#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()

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().

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!

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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