c++ 线程
std::thread
- 头文件
#include <thread>
。 - 用于创建并控制线程。
- 顶层函数:线程需要运行的函数。
- 顶层函数作为构造函数参数传递给该对象。
- 对象构造时,线程以顶层函数作为入口函数并开始运行(等待任何OS调度延迟)。
- 顶层函数的返回值将被忽略,但仍有其他方法可以获取其返回值,比如修改共享变量或使用
std::promise
等。 - 顶层函数若以抛出异常中止,则调用
std::terminate
。 - 对于
joinable
的线程对象,不再需要该线程时,调用者必须调用其join
方法终止线程,否则该线程对象析构时会调用std::terminate
。 - 没有任何两个 std::thread 对象会表示同一执行线程。
- std::thread 对象也可能处于不表示任何线程的状态(默认构造、被移动、 detach 或 join 后),并且执行线程可能与任何 thread 对象无关( detach 后)。
std::thread 成员函数
joinable
:检查线程是否可合并。get_id
:获取线程 id。native_handle
:返回底层实现定义的线程句柄。hardware_concurrency
:返回实现支持的并发线程数。join
:等待线程完成其执行。detach
:分离线程。
std::thread 最常用构造函数
-
函数原型:
template< class Function, class... Args > explicit thread(Function&& f, Args&&... args);
- f:任何可调用对象。
- args:传递给 f 的参数。
-
构造新对象并将它与执行线程关联。
示例1 函数作为参数
#include <stdio.h>
#include <thread>
#include <chrono>
void f1(int n, int& b)
{
for (int i = 0; i < 3; ++i) {
printf("thread is running\n");
++n;
++b;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
printf("in thread, n is %d, b is %d\n", n, b);
}
int main()
{
int n = 0;
int b = 0;
// n 按值传递,b 按引用传递
std::thread t1(f1, n, std::ref(b));
t1.join();
printf("in main, n is %d, b is %d\n", n, b);
return 0;
}
示例2 lamba 作为参数
int main()
{
std::thread t1([](){
for (int i = 0; i < 3; ++i) {
printf("thread is running\n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
t1.join();
return 0;
}
示例3 类的成员函数作为参数
#include <stdio.h>
#include <thread>
#include <chrono>
class foo {
public:
void bar()
{
for (int i = 0; i < 3; ++i) {
printf("thread is running\n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
};
int main()
{
foo f;
std::thread t1(&foo::bar, &f);
t1.join();
return 0;
}
示例4 可调用对象作为参数
#include <stdio.h>
#include <thread>
#include <chrono>
class baz
{
public:
void operator()()
{
for (int i = 0; i < 3; ++i) {
printf("thread is running\n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
};
int main()
{
baz b;
// 调用 baz::operator()
std::thread t1(b);
t1.join();
return 0;
}
示例5 std::function 作为参数
#include <stdio.h>
#include <thread>
#include <chrono>
#include <functional>
int main()
{
std::function<void(void)> func = [](){
for (int i = 0; i < 3; ++i) {
printf("thread is running\n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
};
std::thread t1(func);
t1.join();
return 0;
}