简介
自从c++11开始,使用std::thread类创建线程是非常方便的。
- 类thread关联的对象构造后立即执行(当然会有操作系统调试延迟)
- 作为构造函数参数的函数的返回值将被忽略
- 如果函数通过抛出异常终止,则调用std::terminate
- 但函数可通过std::promise或通过修改共享变量(可能需要同步,请参见std::mutex和std::atomic)将其返回值或异常传达给调用方
注意以下几点:
- 线程对象是不可复制的,只能移动
- 线程对象要么被join,要么detach,否则可能会导致崩溃
thread支持的对象参数类型如下:
- 普通函数
- 成员函数
- 函数对象
- Lambda表达式
普通函数
在独立线程中执行函数:
#include <iostream>
#include <thread>
void foo(int a)
{
std::cout << a << '\n';
}
int main()
{
// Create and execute the thread
std::thread thread(foo, 10); // foo is the function to execute, 10 is the
// argument to pass to it
// Keep going; the thread is executed separately
// Wait for the thread to finish; we stay here until it is done
thread.join();
return 0;
}
成员函数
在独立线程上执行成员函数:
#include <iostream>
#include <thread>
class Bar
{
public:
void foo(int a)
{
std::cout << a << '\n';
}
};
int main()
{
Bar bar;
// Create and execute the thread
std::thread thread(&Bar::foo, &bar, 10); // Pass 10 to member function
// The member function will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
return 0;
}
函数对象
直接上代码:
#include <iostream>
#include <thread>
class Bar
{
public:
void operator()(int a)
{
std::cout << a << '\n';
}
};
int main()
{
Bar bar;
// Create and execute the thread
std::thread thread(bar, 10); // Pass 10 to functor object
// The functor object will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
return 0;
}
Lambda表达式
代码如下:
#include <iostream>
#include <thread>
int main()
{
auto lambda = [](int a) { std::cout << a << '\n'; };
// Create and execute the thread
std::thread thread(lambda, 10); // Pass 10 to the lambda expression
// The lambda expression will be executed in a separate thread
// Wait for the thread to finish, this is a blocking operation
thread.join();
return 0;
}