初探C++11 Thread
来源:互联网 发布:淘宝反渗透膜 编辑:程序博客网 时间:2024/06/02 00:31
Thread
开启一个线程
使用c++11开启一个线程是比较简单的,如下:
#include<iostream>#include<thread>using namespace std;void hello(){ cout<<"hello kitty"<<endl;}int main(){ std::thread t(hello); t.join(); return 0;}
输出结果:
也可以通过函数对象的方式
#include<iostream>#include<thread>using namespace std;class Say_hello{public: void operator()(){cout<<"hello";}};int main(){ Say_hello hello; std::thread t(hello); t.join(); return 0;}
输出结果:
带参数的函数
当函数自身有参数时,形参可以直接写在开启线程的函数参数的后面,如:
thread t( function , t1 , t2 , ...)
比如说下面这2个例子
#include<iostream>#include<thread>using namespace std;class Say_hello{public: enum {times = 2}; void operator()(int n = times) { for(int i=0;i!=n;i++) cout<<"hello"<<endl; }};int main(){ Say_hello hello; std::thread t(hello); t.join(); return 0;}
不带参数时,输出结果为:
带参数时,输出结果为:
int main(){ Say_hello hello; std::thread t(hello,5); t.join(); return 0;}
锁的实现
多线程为了实现线程安全,当访问共享数据时,要避免几个线程同时访问,以免造成竞争条件(race condition)
下面举了一个简单的例子,用锁来实现同步。
一共10张票,开4个线程来卖票。
#include<iostream>#include<thread>#include<mutex>using namespace std;int tickets_count = 10;mutex a_mutex;void sale(){ lock_guard<mutex> guard(a_mutex); //a_mutex.lock(); while(tickets_count>0) { cout<<tickets_count--<<endl; } //a_mutex.unlock();}int main(){ std::thread t1(sale); std::thread t2(sale); std::thread t3(sale); std::thread t4(sale); t1.join(); t2.join(); t3.join(); t4.join(); return 0;}
如果不加锁,可能造成重复,输出混乱(std::out 也不是线程安全)
通过对临界区加锁来尽量实现线程安全。
输出结果为:
10 1
- 初探C++11 Thread
- c++11 Thread库初探
- Thread初探
- C++11 并发编程教程 - Part 1 : thread 初探
- Thread(C#)
- c thread
- thread.c
- select初探(c/c++)
- Zephyr程序初探(5):thread程序
- C#网络编程初探
- C#网络编程初探
- C#网络编程初探
- C#网络编程初探
- C语言指针初探
- C#网络编程初探
- 初探C++(第一步)
- C++_STL_stack_初探
- rabbitmq-c初探
- redis java
- hive基本操作
- hadoop学习【8】——基于hadoop的分词程序二(ICTCLAS分词器)
- tableView滑动很卡的原因
- php等号(==)与全等(===)
- 初探C++11 Thread
- 获取唯一标识UUID UDID
- Android中滑屏初探 - scrollTo 以及 scrollBy方法使用说明
- (二分图最大匹配) poj3041 Asteroids
- 对AlloyAnimation的理解
- ARM 汇编指令集
- SPOJ2666--Query On a Tree Ⅳ
- 机器学习算法汇总:人工神经网络、深度学习及其它
- STC-ISP快捷键