C++ Thread join

Introduction

The .join() member function says: "hey, main thread, please wait for me to finish my work before continuing with yours." If we left out the.join() function, the main thread would finish executing before the t1 thread has finished its work.

We avoid this by joining the child thread to the main thread.

If our function accepts parameters, we can pass those parameters when constructing the std::thread object:

#include <iostream> 
#include <thread> 
#include <string> 

void function1(const std::string& param) 
{ 
    for (int i = 0; i < 10; i++) 
    { /*  w  w  w  .  j ava 2 s . com*/
        std::cout << "Executing function1, " << param << '\n'; 
    } 
} 

int main() 
{ 
    std::thread t1{ function1, "Hello World from a thread." }; 
    t1.join(); 
} 

We can spawn multiple threads in our program/process by constructing multiple std::thread objects.

An example where we have two threads executing two different functions concurrently/simultaneously:

#include <iostream> 
#include <thread> 

void function1() 
{ 
    for (int i = 0; i < 10; i++) 
    { /*from  ww  w .j a v  a 2 s .  com*/
        std::cout << "Executing function1." << '\n'; 
    } 
} 

void function2() 
{ 
    for (int i = 0; i < 10; i++) 
    { 
        std::cout << "Executing function2." << '\n'; 
    } 
} 

int main() 
{ 
    std::thread t1{ function1 }; 
    std::thread t2{ function2 }; 

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

This example creates two threads executing two different functions concurrently.

The function1 code executes in a thread t1, and the function2 code executes in a separate thread called t2.

We can also have multiple threads executing code from the same function concurrently:

#include <iostream> 
#include <thread> 
#include <string> 

void myfunction(const std::string& param) 
{ 
    for (int i = 0; i < 10; i++) 
    { //from w  w  w  .  j  a  v  a 2 s .co m
        std::cout << "Executing function from a " << param << '\n'; 
    } 
} 

int main() 
{ 
    std::thread t1{ myfunction, "Thread 1" }; 
    std::thread t2{ myfunction, "Thread 2" }; 

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



PreviousNext

Related