Zak Zak - 1 year ago 57
C++ Question

Simple example of threading in C++

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.

Update - 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.

Answer Source

Create a function that you want the thread to execute. I'll demonstrate with a trivial 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 <thread> to access the std::thread class)

As you can see, the constructor's arguments are the function the thread will execute, followed by the function's parameters.

Finally, join it to your main thread of execution like so:


(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 <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");

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download