Multithreading Three Ways to Create Threads

C++11 Multithreading – Part 1 : Three Different ways to Create Threads

Thread Creation in C++11

每个C++应用中都存在一个默认的主线程——main()函数。在C++11中,我们可以通过创建std::thread的对象类创建额外的线程。头文件为:

1
#include <thread>

What std::thread accepts in constructor ?

我们可以为std::thread对象附上一个callback,在线程开始时执行,这些callbacks可以是:

  1. Function Pointer
  2. Function Objects
  3. Lambda functions

调用方式如下:

1
std::thread theObj(<CALLBACK>)

新的线程会在对象创建出来之后开始运行,并且会并行地执行传递进来的回调。此外,任何线程都可以通过调用该线程对象上的join()函数来等待另一个线程退出。

让我们来看看三种不同的回调机制:

1
2
3
4
5
6
void thread_function(){...}

int main()
{
std::thread threadObj(thread_function);
}
1
2
3
4
5
6
7
8
9
10
class DisplayThread
{
public:
void operator()(){...}
};

int main()
{
std::thread threadObj(DisplayThread());
}
1
std::thread threadObj([]{...});

Differentiating between threads

每个std::thread对象都有一个关联的ID。

以下成员函数给出了关联的线程对象ID:

1
std::thread::get_id()

要得到当前线程的ID,可以通过:

1
std::this_thread::get_id()