Open In App

How to Join a Thread in C++?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a thread is a basic element of multithreading that represents the smallest sequence of instructions that can be executed independently by the CPU. In this article, we will discuss how to join a thread in C++.

How to Join a Thread in C++?

Joining a thread is a means to wait for the thread to complete its execution before moving to the next part of the program.

We can join the thread using the std::thread::join() function. It is a member function that makes sure that the execution of the thread is complete before moving on to the next statement after the join() function call.

C++ Program to Join a Thread

C++
// C++ Program to illustrate how to join a thread
#include <iostream>
#include <thread>
using namespace std;
// Define a function to be executed by the thread
void myFunction()
{
    cout << "Thread started" << endl;
    // Do some work
    cout << "Thread finished" << endl;
}

int main()
{
    // Print a message indicating the start of the main
    // thread
    cout << "Main thread started" << endl;

    // Create a new thread and associate it with the
    // function myFunction
    thread myThread(myFunction);

    // Wait for the created thread (myThread) to finish
    // execution
    myThread.join();
    cout << "Main thread finished" << endl;

    return 0;
}

Output:

Main thread started
Thread started
Thread finished
Main thread finished



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads