C++11并发之std::thread<转>
最近技术上没什么大的收获,也是悲催的路过~
搞一点新东西压压惊吧!
- id
- Thread id (public member type ) id
- native_handle_type
- Native handle type (public member type )
成员函数:
- (constructor)
- Construct thread (public member function ) 构造函数
- (destructor)
- Thread destructor (public member function ) 析构函数
- operator=
- Move-assign thread (public member function ) 赋值重载
- get_id
- Get thread id (public member function ) 获取线程id
- joinable
- Check if joinable (public member function ) 判断线程是否可以加入等待
- join
- Join thread (public member function ) 加入等待
- detach
- Detach thread (public member function ) 分离线程
- swap
- Swap threads (public member function ) 线程交换
- native_handle
- Get native handle (public member function ) 获取线程句柄
- hardware_concurrency [static]
- Detect hardware concurrency (public static member function ) 检测硬件并发特性
Non-member overloads:
- swap (thread)
- Swap threads (function )
- default (1)
- thread() noexcept;
- initialization(2)
- template <class Fn, class... Args> explicit thread (Fn&& fn, Args&&... args);
- copy [deleted] (3)
- thread (const thread&) = delete;
- move [4]
- hread (thread&& x) noexcept;
#include<thread>
#include<chrono>
using namespace std;
void fun1(int n) //初始化构造函数
{
cout << "Thread " << n << " executing\n";
n += ;
this_thread::sleep_for(chrono::milliseconds());
}
void fun2(int & n) //拷贝构造函数
{
cout << "Thread " << n << " executing\n";
n += ;
this_thread::sleep_for(chrono::milliseconds());
}
int main()
{
int n = ;
thread t1; //t1不是一个thread
thread t2(fun1, n + ); //按照值传递
t2.join();
cout << "n=" << n << '\n';
n = ;
thread t3(fun2, ref(n)); //引用
thread t4(move(t3)); //t4执行t3,t3不是thread
t4.join();
cout << "n=" << n << '\n';
return ;
}
运行结果:
Thread executing
n=
Thread executing
n=</span>
#include<thread>
using namespace std;
void show()
{
cout << "hello cplusplus!" << endl;
}
int main()
{
//栈上
thread t1(show); //根据函数初始化执行
thread t2(show);
thread t3(show);
//线程数组
thread th[]{thread(show), thread(show), thread(show)};
//堆上
thread *pt1(new thread(show));
thread *pt2(new thread(show));
thread *pt3(new thread(show));
//线程指针数组
thread *pth(new thread[]{thread(show), thread(show), thread(show)});
return ;
}
#include<thread>
using namespace std;
void show(const char *str, const int id)
{
cout << "线程 " << id + << " :" << str << endl;
}
int main()
{
thread t1(show, "hello cplusplus!", );
thread t2(show, "你好,C++!", );
thread t3(show, "hello!", );
return ;
}
运行结果:
线程 1线程 :你好,C++!线程 :hello!
:hello cplusplus!
#include<thread>
#include<array>
using namespace std;
void show()
{
cout << "hello cplusplus!" << endl;
}
int main()
{
array<thread, > threads = { thread(show), thread(show), thread(show) };
for (int i = ; i < ; i++)
{
cout << threads[i].joinable() << endl;//判断线程是否可以join
threads[i].join();//主线程等待当前线程执行完成再退出
}
return ;
}
运行结果:
hello cplusplus!
hello cplusplus! hello cplusplus!
#include<thread>
using namespace std;
void show()
{
cout << "hello cplusplus!" << endl;
}
int main()
{
thread th(show);
//th.join();
th.detach();//脱离主线程的绑定,主线程挂了,子线程不报错,子线程执行完自动退出。
//detach以后,子线程会成为孤儿线程,线程之间将无法通信。
cout << th.joinable() << endl;
return ;
}
运行结果:
hello cplusplus!
#include<thread>
using namespace std;
int main()
{
auto n = thread::hardware_concurrency();//获取cpu核心个数
cout << n << endl;
return ;
}
运行结果:
#include<thread>
using namespace std;
const int N = ;
int num = ;
void run()
{
for (int i = ; i < N; i++)
{
num++;
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ",用时 " << end - start << " ms" << endl;
return ;
}
运行结果:
num=,用时 ms
#include<thread>
#include<mutex>
using namespace std;
const int N = ;
int num();
mutex m;
void run()
{
for (int i = ; i < N; i++)
{
m.lock();
num++;
m.unlock();
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ",用时 " << end - start << " ms" << endl;
return ;
}
运行结果:
num=,用时 ms
#include<thread>
#include<atomic>
using namespace std;
const int N = ;
atomic_int num{ };//不会发生线程冲突,线程安全
void run()
{
for (int i = ; i < N; i++)
{
num++;
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ",用时 " << end - start << " ms" << endl;
return ;
}
运行结果:
num=,用时 ms
#include<thread>
using namespace std;
const int N = ;
int num = ;
void run()
{
for (int i = ; i < N; i++)
{
num++;
}
}
int main()
{
clock_t start = clock();
thread t1(run);
t1.join();
thread t2(run);
t2.join();
clock_t end = clock();
cout << "num=" << num << ",用时 " << end - start << " ms" << endl;
return ;
}
运行结果:
num=,用时 ms
#include<thread>
using namespace std;
int main()
{
auto fun = [](const char *str) {cout << str << endl; };
thread t1(fun, "hello world!");
thread t2(fun, "hello beijing!");
return ;
}
运行结果:
hello world!
hello beijing!
#include<thread>
#include<chrono>
using namespace std;
int main()
{
thread th1([]()
{
//让线程等待3秒
this_thread::sleep_for(chrono::seconds());
//让cpu执行其他空闲的线程
this_thread::yield();
//线程id
cout << this_thread::get_id() << endl;
});
return ;
}
#include<thread>
using namespace std;
class MyThread :public thread //继承thread
{
public:
//子类MyThread()继承thread()的构造函数
MyThread() : thread()
{
}
//MyThread()初始化构造函数
template<typename T, typename...Args>
MyThread(T&&func, Args&&...args) : thread(forward<T>(func), forward<Args>(args)...)
{
}
void showcmd(const char *str) //运行system
{
system(str);
}
};
int main()
{
MyThread th1([]()
{
cout << "hello" << endl;
});
th1.showcmd("calc"); //运行calc
//lambda
MyThread th2([](const char * str)
{
cout << "hello" << str << endl;
}, " this is MyThread");
th2.showcmd("notepad");//运行notepad
return ;
}
运行结果:
hello
//运行calc
hello this is MyThread
//运行notepad
#include<thread>
#include<cstdarg>
using namespace std;
int show(const char *fun, ...)
{
va_list ap;//指针
va_start(ap, fun);//开始
vprintf(fun, ap);//调用
va_end(ap);
return ;
}
int main()
{
thread t1(show, "%s %d %c %f", "hello world!", , 'A', 3.14159);
return ;
}
运行结果:
hello world! A 3.14159
#include<thread>
using namespace std;
int main()
{
thread t1([]()
{
cout << "thread1" << endl;
});
thread t2([]()
{
cout << "thread2" << endl;
});
cout << "thread1' id is " << t1.get_id() << endl;
cout << "thread2' id is " << t2.get_id() << endl; cout << "swap after:" << endl;
swap(t1, t2);//线程交换
cout << "thread1' id is " << t1.get_id() << endl;
cout << "thread2' id is " << t2.get_id() << endl;
return ;
}
运行结果:
thread1
thread2
thread1' id is 4836
thread2' id is 4724
swap after:
thread1' id is 4724
thread2' id is 4836
#include<thread>
using namespace std;
int main()
{
thread t1([]()
{
cout << "thread1" << endl;
});
cout << "thread1' id is " << t1.get_id() << endl;
thread t2 = move(t1);;
cout << "thread2' id is " << t2.get_id() << endl;
return ;
}
运行结果:
thread1
thread1' id is 5620
thread2' id is 5620
从上述代码中,线程t2可以通过 move 移动 t1 来获取 t1 的全部属性,而 t1 却销毁了。
原贴地址:https://www.cnblogs.com/lidabo/p/7852033.html
C++11并发之std::thread<转>的更多相关文章
- c++11并发之std::thread
知识链接: https://www.cnblogs.com/lidabo/p/7852033.html 构造函数如下: ) thread() noexcept; initialization() te ...
- C++11 并发之std::thread std::mutex
https://www.cnblogs.com/whlook/p/6573659.html (https://www.cnblogs.com/lidabo/p/7852033.html) C++:线程 ...
- C++11并发之std::mutex
知识链接: C++11并发之std::thread 本文概要: 1. 头文件. 2.std::mutex. 3.std::recursive_mutex. 4.std::time_mutex. 5 ...
- C++11 并发指南------std::thread 详解
参考: https://github.com/forhappy/Cplusplus-Concurrency-In-Practice/blob/master/zh/chapter3-Thread/Int ...
- C++11并发——多线程std::thread (一)
https://www.cnblogs.com/haippy/p/3284540.html 与 C++11 多线程相关的头文件 C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是< ...
- c++11中关于std::thread的join的思考
c++中关于std::thread的join的思考 std::thread是c++11新引入的线程标准库,通过其可以方便的编写与平台无关的多线程程序,虽然对比针对平台来定制化多线程库会使性能达到最大, ...
- c++11中关于`std::thread`线程传参的思考
关于std::thread线程传参的思考 最重要要记住的一点是:参数要拷贝到线程独立内存中,不管是普通类型.还是引用类型. 对于传递参数是引用类型,需要注意: 1.当指向动态变量的指针(char *) ...
- C++ 11 笔记 (五) : std::thread
这真是一个巨大的话题.我猜记录完善绝B需要一本书的容量. 所以..我只是略有了解,等以后用的深入了再慢慢补充吧. C++写多线程真是一个痛苦的事情,当初用过C语言的CreateThread,见过boo ...
- Cocos2dx 3.0 过渡篇(二十六)C++11多线程std::thread的简单使用(上)
昨天练车时有一MM与我交替着练,聊了几句话就多了起来,我对她说:"看到前面那俩教练没?老色鬼两枚!整天调戏女学员."她说:"还好啦,这毕竟是他们的乐趣所在,你不认为教练每 ...
随机推荐
- 峰Redis学习(7)Redis 持久化RDB方式
第一节:Redis 持久化介绍 redis所有的数据都存在内存中,所以速度非常快,但是一旦断电等情况,数据就没了.从内存当中同步到硬盘上,这个过程叫做持久化过程. 持久化操作,两种方式:rdb方式.a ...
- 传统Java Web(非Spring Boot)、非Java语言项目接入Spring Cloud方案
技术架构在向spring Cloud转型时,一定会有一些年代较久远的项目,代码已变成天书,这时就希望能在不大规模重构的前提下将这些传统应用接入到Spring Cloud架构体系中作为一个服务以供其它项 ...
- etcd集群部署与遇到的坑(转)
原文 https://www.cnblogs.com/breg/p/5728237.html etcd集群部署与遇到的坑 在k8s集群中使用了etcd作为数据中心,在实际操作中遇到了一些坑.今天记录一 ...
- [UE4]Grid Panel
一.使用Grid Panel可以做出类似暗黑3一样的物品栏:不同的物品栏占据的物品栏格子不一样. 二.GridPanel.FillRules,可以设置每个单元格内的控件是否是拉伸比重.注意:这个是Gr ...
- [UE4]The global shader cache file missing 运行错误解决办法
UE4项目在VS中对项目代码编译时报如错,找了好久在UE4论坛上查到了别人的解决方案,贴出来仅供大家参考. 看到一位开发者解释出错的原因如下: There are a number of build ...
- github webhook 实现代码自动部署 踩坑!! 附加git&coding webhook部署代码
踩坑: 1.php程序执行linux命令是以webserver的user用户(如apache .www……)操作的,需要在/etc/sudoers添加用户免密码操作权限; %apache ALL=(A ...
- SCCM2012 R2实战系列之五:发现方法
打开SCCM2012的控制台 点击左侧栏的“管理”选项,然后展开“层次结构配置”,点击“发现方法”来配置客户端发现. 勾选“启用Active Directory林发现”.“发现Active Direc ...
- SQLServer: 解决“错误15023:当前数据库中已存在用户或角色”
首先介绍一下sql server中“登录”与“用户”的区别,“登录”用于用户身份验证,而数据库“用户”帐户用于数据库访问和权限验证.登录通过安全识别符 (SID) 与用户关联.将数据库恢复到其他服务器 ...
- 第9章 应用层(4)_超文本传输协议HTTP
5. 超文本传输协议HTTP 5.1 统一资源定位符URL (1)URL的一般形式:<协议>://<主机>:<端口>/<路径> ①协议后面必须写上“:/ ...
- Java基础方面
1.作用域public,private,protected,以及不写时的区别 答:区别如下: 作用域 当前类 同一package 子孙类 其他package ...