[C++] C++11 thread线程库

本文介绍了C++11的thread线程库,它对原生的pthread库进行了封装,提供了更灵活的线程创建方式。通过thread类,可以方便地传入线程执行函数和参数。主要内容包括thread类的主要方法如获取线程ID、判断是否可加入、join和detach,以及简单的线程创建代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thread 类

C++11的支持的thread线程库对原生的pthread库进行了封装,原本pthread_create函数只能传递一个参数,而新的thread类更为灵活。

部分构造函数如下,其中复制构造函数都已处于delete状态,不再使用:

thread() noexcept = default;
thread(thread&& __t) noexcept // 移动构造函数

template<typename _Callable, typename... _Args>	// 这里还用到了C++11的可变模板参数
      explicit thread(_Callable&& __f, _Args&&... __args)

thread(_Callable&& __f, _Args&&... __args),可以传入线程执行函数的同时直接传入可变的参数,比起原生pthread库实在方便很多。

thread 类主要方法

  • get_id() ——获取线程ID,返回类型std::thread::id对象。参考get_id
  • joinable() ——判断线程是否可以加入等待。参考joinable
  • join() ——等该线程执行完成后才返回。参考join
  • detach() ——将本线程从调用线程中分离出来,允许本线程独立执行。(当主进程结束时,不管子进程是否detach()都会被杀死)。参考detach

简单创建线程的代码示例

由于用到pthread库,因此编译时要加-lpthread选项。

#include <iostream>
#include <thread>
using namespace std;

void work1()
{
    cout << "This is work1\n";
}
void work2(int a, int b)
{
    cout << "work2 a + b = " << a + b << endl;
}

int main()
{
    thread t1(work1);
    cout << "thread id " << t1.get_id() << " running...\n";
    if(t1.joinable())
        t1.join();

    thread t2(work2, 1, 2);	// 可直接传右值参数
    cout << "thread id " << t2.get_id() << " running...\n";
    if(t2.joinable())
        t2.join();
}

输出:

thread id This is work1		# 此处由于线程交替执行打印出现混乱
139923688707840 running...
thread id 139923688707840 running...
work2 a + b = 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值