std::thread

📅 2026/7/2 10:59:05
std::thread
C 11 提供的 std::thread 类无论是 Linux 还是 Windows 上创建线程的 API都有一个非常不方便的地方就是线程函数的签名必须是固定的格式参数个数和类型、返回值类型都有要求。C11 新标准引入了一个新的类std::thread需要包含头文件thread使用这个类的可以将任何签名形式的函数作为线程函数。以下代码分别创建两个线程线程函数签名不一样#include stdio.h #include thread void threadproc1() { while (true) { printf(I am New Thread 1!\n); } } void threadproc2(int a, int b) { while (true) { printf(I am New Thread 2!\n); } } int main() { //创建线程t1 std::thread t1(threadproc1); //创建线程t2 std::thread t2(threadproc2, 1, 2); while (true) { //Sleep(1000); //权宜之计让主线程不要提前退出 } return 0; }当然std::thread在使用上容易犯一个错误即在std::thread对象在线程函数运行期间必须是有效的。什么意思呢我们来看一个例子#include stdio.h #include thread void threadproc() { while (true) { printf(I am New Thread!\n); } } void func() { std::thread t(threadproc); } int main() { func(); while (true) { //Sleep(1000); //权宜之计让主线程不要提前退出 } return 0; }上述代码在func中创建了一个线程然后又在main函数中调用func方法乍一看好像代码没什么问题但是在实际运行时程序会崩溃。崩溃的原因是当func函数调用结束后func中局部变量t线程对象被销毁了而此时线程函数仍然在运行。这就是我所说的使用std::thread类时必须保证线程函数运行期间其线程对象有效。这是一个很容易犯的错误解决这个问题的方法是std::thread对象提供了一个detach方法这个方法让线程对象与线程函数脱离关系这样即使线程对象被销毁仍然不影响线程函数的运行。我们只需要在在func函数中调用detach方法即可代码如下//其他代码保持不变这里就不重复贴出来了 void func() { std::thread t(threadproc); t.detach(); }然而在实际编码中这也是一个不推荐的做法原因是我们需要使用线程对象去控制和管理线程的运行和生命周期。所以我们的代码应该尽量保证线程对象在线程运行期间有效而不是单纯地调用detach方法使线程对象与线程函数的运行分离。