C++11中的线程简介
2016-02-25 21:10
507 查看
/* * 学习线程 */ #include "stdafx.h" #include <iostream> #include <ctime> #include <cassert> #include <atomic> #include <thread> // C++11的时间类 #include <chrono> // 参数-长模板 #include <tuple> using namespace std; // 原子模板 atomic<long long> total = {0}; // 独立线程函数,可以操作原子模板 void func(decltype(make_tuple("hello", 123)) str) { // 获取tuple中的值 cout << get<0>(str) << endl; cout << get<1>(str) << endl; // 当前线程休息1000毫秒 this_thread::sleep_for(chrono::milliseconds(1000)); // 让当前线程让出一段时间 this_thread::yield(); // 获取当前线程的id this_thread::get_id(); // 获取当前时间 time_t tm = time(NULL); // 转化为tm结构体 auto now = make_shared<struct tm>(); localtime_s(now.get(),&tm); // 将tm结构体中的秒+20 now->tm_sec += 20; // 再把tm结构体转化为time_t time_t tmm = mktime(now.get()); // 调用时间类,把time_t转化为chrono::time_point类型 auto time = chrono::system_clock::from_time_t(tmm); // 让当前线程休息到当前时间之后的20秒 this_thread::sleep_until(time); for (long long i = 0L; i < 10000000L;++i) { ++total; } }; int main() { // 生产一个tuple对象 auto str1 = make_tuple("hello", 123); auto str2 = make_tuple("world", 456); // 新建一个线程 thread t1(func, str1); thread t2(func, str2); // 获取线程的id,类型为thread::id cout << t1.get_id() << ":" << t2.get_id() << endl; // 检测硬件并发特性 cout << t1.hardware_concurrency() << endl; // 将t1和t2交换 t1.swap(t2); cout << t1.get_id() << ":" << t2.get_id() << endl; // 判断线程t1是否可以被join assert(t1.joinable()); // 等待线程结束 t1.join(); t2.join(); cout << total << endl; return 0; }
二、互斥锁:mutex
/* * 学习线程 */ #include "stdafx.h" #include <iostream> // 互斥锁 #include <mutex> #include <thread> using namespace std; mutex mt; void func(decltype(make_tuple("t1", make_shared<int>())) str) { cout << get<0>(str) << endl; mt.lock(); *get<1>(str) += 1; mt.unlock(); } int main() { auto i = make_shared<int>(1); auto mt1 = make_tuple("t1", i); auto mt2 = make_tuple("t2", i); thread t1(func, mt1); thread t2(func, mt2); t1.join(); t2.join(); cout << *i << endl; return 0; }
相关文章推荐
- C语言静态函数静态变量
- new与malloc的区别
- C++注意点(第二部分)
- HDU5631并查集检验图连通
- C语言实现链表节点的插入
- 理解C语言——从小菜到大神的晋级之路(11)——文件输入输出
- 找出字符串中第一个只出现一次的字符
- c语言生成 o~100随机数!
- c++中类的多态和虚函数的使用
- 20160211.CCPP体系详解(0021天)
- c语言字符串 数字转换函数大全
- 20160210.CCPP体系详解(0020天)
- C语言运算优先级
- C++STL中的标准模板——优先队列
- 俄罗斯方块C++源码
- c++中使用struct,struct中有指针
- C++中vector模板详解
- 20160209.CCPP体系详解(0019天)
- 1050. String Subtraction (20)
- C语言函数调用机制