您的位置:首页 > 编程语言 > C语言/C++

C++11 多线程编程

2016-05-03 12:16 639 查看
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还有递归互斥变量,超时互斥变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++11 特性 多线程