HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

Simple example of threading in C++

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
simpleexamplethreading

Problem

Can someone post a simple example of starting two (Object Oriented) threads in C++.

I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.

I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.

Solution

Create a function that you want the thread to execute, for example:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}


Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");


(You need to #include to access the std::thread class.)

The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join();


(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)

The Code

#include 
#include 
#include 

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}


More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.



  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

Code Snippets

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}
std::thread t1(task1, "Hello");
#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

Context

Stack Overflow Q#266168, score: 735

Revisions (0)

No revisions yet.