Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of Thread.Join in C#?

What is the significance of the Thread.Join method in C#?

MSDN says that it blocks the calling thread until a thread terminates. Can anybody explain this with a simple example?

like image 714
Techee Avatar asked Mar 19 '10 10:03

Techee


People also ask

What is the purpose of thread join?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

What does joining threads do in C?

Joining a thread means waiting for it to terminate, which can be seen as a specific usage of condition variables. Using the pthread_join subroutine alows a thread to wait for another thread to terminate.

Is thread join necessary?

It is perfectly fine. No join or System. exit necessary. Each thread lives its own life.

Why do we need threads in C?

Threads operate faster than processes due to following reasons: 1) Thread creation is much faster. 2) Context switching between threads is much faster. 4) Communication between threads is faster.


2 Answers

Join() is basically while(thread.running){}

{
  thread.start()
  stuff you want to do while the other thread is busy doing its own thing concurrently
  thread.join()
  you won't get here until thread has terminated.
} 
like image 168
Spike Avatar answered Sep 27 '22 16:09

Spike


int fibsum = 1;

Thread t = new Thread(o =>
                          {
                              for (int i = 1; i < 20; i++)
                              {
                                  fibsum += fibsum;
                              }
                          });

t.Start();
t.Join(); // if you comment this line, the WriteLine will execute 
          // before the thread finishes and the result will be wrong
Console.WriteLine(fibsum);
like image 44
andreialecu Avatar answered Sep 27 '22 18:09

andreialecu