C++多线程入门基础,含示例代码

线程基本知识

  • 多线程库:#include
  • join():加入、汇合线程,阻塞主线程;
  • detach():分离,驻留后台;
  • 注意点:对于同一个线程而言,join()和detach()只能做一次

创建线程的方式

  1. 普通函数充当线程处理函数;
void print_1()
{
   cout<<"俺是一个线程"<<endl;
}
//测试函数,记得在主函数中调用
void test_1()
{
   thread t1(print_1);
   t1.join();
}
  1. 采用纳母达表达式充当线程处理函数;
void test_2()
{
   thread t1([](){cout<<"纳母达表达式充当线程处理函数";});
   t1.join();
}
  1. 带参函数创建线程
    3.1 普通函数带参函数
    3.2 以引用作为函数参数的函数
    3.3 智能指针充当函数参数
void print_2(int num)
{
   cout<<"id: "<<num<<endl;
}
void test_3()
{
   int num=1213;
   thread t1(print_2,num);
   t1.join();
}
void print_3(int& num)
{
   num=1314;
   cout<<"id: "<<num<<endl;
}
void test_4()
{
   int num=0;
   thread t1(print_3,ref(num));
   //ref:包装引用作为传递的值,不包装会报错,invoke:未找到匹配的重载函数
   t1.join();
   cout<<"主线程:"<<num<<endl;
}
void print_4(unique_ptr<int>ptr)
{
   cout<<"智能指针:"<<*ptr.get()<<endl;
}
void test_5()
{
   unique_ptr<int>ptr(new int(999));
   cout<<"intelligence:"<<*ptr.get()<<endl;
   thread t1(print_4,move(ptr));
   //move函数作用是移交权限
   cout<<"intelligence:"<<*ptr.get()<<endl;
   //权限移交移交,此时打印ptr的值,为空或者其他超大超小数字
  1. 类中成员函数作为线程处理函数,仿函数形式:类名的方式调用
class Function
{
public:
   void operator()()
   {
      cout<<"重载()号"<<endl;
   }
};
void test_6()
{
   //传对象
   Function object;
   thread t1(object);
   t1.join();
   //传匿名对象
   thread  t2((Function()));
   t2.join(); 
  1. 普通类中的成员函数
class Common
{
public:
   void print(int& id)
   {
      cout<<"id: "<<id<<endl;
   }
};

void test_7()
{
   Common com;
   int id=1213;
   thread t1(&Common::print,com,ref(id));
   t1.join();
}   
结语
  • 以上就是我所学习到线程创建的方式,如有错误或缺省,还请小伙伴不吝赐教;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值