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);*/
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还有递归互斥变量,超时互斥变量。
#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还有递归互斥变量,超时互斥变量。
相关文章推荐
- Python3写爬虫(四)多线程实现数据爬取
- C#实现多线程的同步方法实例分析
- 浅谈chuck-lua中的多线程
- C#简单多线程同步和优先权用法实例
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#多线程编程中的锁系统(三)
- 解析C#多线程编程中异步多线程的实现及线程池的使用
- C#多线程学习之(六)互斥对象用法实例
- 基于一个应用程序多线程误用的分析详解
- C#多线程学习之(三)生产者和消费者用法分析
- C#多线程学习之(一)多线程的相关概念分析
- C#多线程之Thread中Thread.IsAlive属性用法分析
- 分享我在工作中遇到的多线程下导致RCW无法释放的问题
- C#多线程编程之使用ReaderWriterLock类实现多用户读与单用户写同步的方法
- C#控制台下测试多线程的方法
- 21天学习android开发教程之SurfaceView与多线程的混搭
- Ruby 多线程的潜力和弱点分析
- C#中WPF使用多线程调用窗体组件的方法
- C#如何对多线程、多任务管理(demo)
- C#实现多线程的Web代理服务器实例