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

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: