C++11多线程std::thread使用记录

构造函数

thread() noexcept;

template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);

thread (const thread&) = delete;

thread (thread&& x) noexcept;

常用方法

 void join();
 void detach();
  • join()等待子线程执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源
  • detach()将子线程从主线程里分离,子线程执行完成后会自己释放掉资源。分离后的线程,主线程将对它没有控制权了

使用前说明

  1. std::thread 在 <thread> 头文件中声明,因此使用 std::thread 时需要包含 <thread> 头文件
  2. 可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.
  3. Unix平台需要增加编译参数-lpthread或者-pthread (推荐)

普通函数实现多线程

void fun(int arg)
{
    cout<<"thread fun:"<<arg<<endl;
}
 std::thread t1(fun,1024);
 t1.join();

类成员函数

class Task
{
public:
    void fun(int id)
    {
        cout<<"Task fun:"<<id<<" "<<this<<endl;
    }
    void fun1(int id,int id2)
    {
        cout<<"Task fun:"<<id<<" "<<id2<<" "<<this<<endl;
    }
};
Task task;
 std::thread t3(&Task::fun,&task,123);
 t3.join();

绑定函数

Task task;
auto fun = std::bind(&Task::fun,&task,456);
std::thread t4(fun);
t4.join();

std::function<void(Task*,int,int)> fun111 =&Task::fun1;
std::thread t5(fun111,&task,1,3);
t5.join();

lambda表达式

std::thread t2([]{std::cout<<"thread1"<<endl;});
t2.join();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值