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:

#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:

#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:

#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:

#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;
}