>

Monday, 14 December 2015

Joining threads:

Joining threads :
Every thread is joinable. In fact, every thread is joinable by default. Best practices concerning thread joining include:
Explicitly declare threads to be joinable or non-joinable when creating:
o To explicitly declare a thread joinable, you must pass in the attribute pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_JOINABLE);
Increase portability by explicitly declaring threads joinable or non-joinable
Improve performance and free up resources by using non-joinable threads when appropriate
When joining threads, it is important to remember the following:
Any thread can call pthread_join().
You must pass in the threadid of the thread that you want to join.
Joining combines two separate threads into one thread.
When a thread is joined, the master thread will get to the pthread_join() and wait until the joined thread completes its work and returns, then the master thread will proceed.
The thread that calls pthread_exit() can return status and pthread_join() can then access that status.
pthread_join() is a wait condition.
o A thread calling pthread_join() will wait until the specified thread terminates and has been “joined” to
The following is an example of how threads may be joined.
From the Master Thread pthread_create() is called.
Two or more worker threads are created to accomplish the work.
pthread_exit() is used to exit the worker threads and return to the Main Thread.
pthread_join() prevents execution of the Master Thread until the worker threads have finished and then resumes Master Thread execution.

Joining threads
It is possible to detach threads even when they have been previously specified as joinable using the following syntax.



The arguments passed in the pthread_join command perform the following functions:
1. Blocks execution until this thread calls pthread_exit()
2. Returns the code of pthread_exit()



In the second loop, pthread_join() is called.
This makes main() wait until the thread is finished and then main() will proceed.
When thread 0 is finished it displays the result.
Main() has been waiting for thread 0 to finish and displays the status of thread 0.
Then the output shows that thread 2 is done, but since main is waiting for thread 1 to complete, nothing happens.
When thread 1 finishes, main shows that thread 1 is finished and has a status of 1.
Then because thread 2 is already done, main immediately shows that thread 2 is finished and has a status of 2.
Then it waits for thread 3 to be finished.
It is important to note the following:
The threads were created in a non-deterministic order.
The threads were run and completed in a non-deterministic order.
The threads were joined in a deterministic order because of the way the code was written.

0 comments:

Post a comment