mario::konrad
programming / C++ / sailing / nerd stuff
Multithreading: Tutorial 08: C++11 Thread creation
© 2012 / Mario Konrad

Introduction

This rather short tutorial shows different ways to create a C++11 thread.

The source can be built using GCC (4.6.1 or newer) using the command:

$ g++ -std=c++0x -o thread-tutorial-8a thread-tutorial8a.cpp -lpthread

Thread Creation

Function

thread-tutorial-8a.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <thread>

static void func()
{
    std::cout << "Hello World" << std::endl;
}

int main(int, char **)
{
    std::thread t(func);
    t.join();
    return 0;
}

Function with Arguments

thread-tutorial-8b.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <thread>

static void func(int a, int b)
{
    std::cout << "Hello World: " << a << ", " << b << std::endl;
}

int main(int, char **)
{
    std::thread t(func, 10, 20);
    t.join();
    return 0;
}

Structure

thread-tutorial-8c.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>

struct Func
{
    void operator()()
    {
        std::cout << "Hello World" << std::endl;
    }
};

int main(int, char **)
{
    Func func;
    std::thread t(func);
    t.join();
    return 0;
}

Class

thread-tutorial-8d.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>

class runnable
{
    public:
        void operator()()
        {
            std::cout << "Hello World" << std::endl;
        }
};

int main(int, char **)
{
    std::thread t(std::move(runnable()));
    t.join();
    return 0;
}