C++11 多线程编程

1.利用C++11线程函数创建线程,

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


void fun(int i)
{
    cout<<"i="<<i<<endl;
}


int main()
{
    for(int i=0;i<4;i++)
    {
        thread t(fun,i);//创建线程函数,参数为函数地址,与函数参数。对于函数还可以通过lambda表达式里处理<pre name="code" class="cpp"><span style="white-space:pre">	</span>/*thread t1([](int a,int b)->string {return "csvevbe";},1,2);*/

 
<span style="white-space:pre">	</span>
        t.join();       //利用join来阻塞线程。


    }
    return 0;
}

2.此外线程还有休眠,获取ID,获取当前CPU核数

#include<iostream>
#include<thread>
#include<windows.h>
using namespace std;

void fun(int i)
{
    for(int x=0;x<i;x++)
    {
         cout<<"i="<<x<<endl;
         Sleep(3000);//暂停3秒  S要大写
    }


}

int main()
{

    thread t1(fun,3);

    cout<<t1.get_id()<<endl;//获取当前线程的ID
    cout<<thread::hardware_concurrency()<<endl;//获取当前CPU的核数

    t1.join();
    cout<<"i want to do something"<<endl;
    return 0;
}
3.利用mutex来互斥

#include<iostream>
#include<thread>
#include<windows.h>
#include<mutex>
using namespace std;

mutex g_lock;

void fun(int i)
{
   g_lock.lock();
   cout<<this_thread::get_id()<<endl;
   Sleep(3000);
   g_lock.unlock();

}

int main()
{

    thread t1(fun,1);
    thread t2(fun,2);

    t1.join();
    t2.join();


    return 0;
}

4.除了基本mutex还有递归互斥变量,超时互斥变量。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值