c++11多线程记录2:线程管理
线程没有调用join和detach
thread对象必须调用join或者detach,否则程序会终止
例如:
void func()
{
std::cout << "hello, " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread t(func);
return 0;
}
也可能在join/detach之前抛出异常导致没有正常调用join/detach
void func()
{
......
}
int main()
{
std::thread t(func);
......
where (......)
{
......
// 这里抛出异常
}
......
t.join();
return 0;
}
上面这段代码在where块里抛出异常导致join没有被调用
解决方法
第一种解决方法是加上try-catch块
......
try {
where () { ...... }
} catch (...) {
if (t.joinable())
t.join();
throw;
}
......
t.join();
......
或者使用RAII,将thread对象放到自定义类型classT中,在classT的析构方法里尝试调用join/detach
class Wrapper
{
public:
......
~Wrapper() { if (m_t.joinable()) m_t.join(); }
......
private:
std::thread m_t;
}
thread可以用任何callable对象构造
thread构造函数的第一个参数可以是任何callable对象:
- 一般的函数调用,如上面func
- 仿函数 Functor
- Lambda函数
void func() { cout << "hello" << endl; }
class Functor
{
public:
void operator()
{
cout << "Functor" << endl;
}
}
int main()
{
...
thread t1(func);
thread t2([](){ cout << "Lambda" << endl });
Functor fct;
thread t3(fct);
thread t4((Functor()));
// 注意这里不能用thread t4(Functor()),会被认为是一个函数声明,函数名为t4,返回值是thread类型的函数
...
// t1~t4调用join/detach
return 0;
}
传参
void func(string s) { cout << s << endl; }
...
string s = "hello";
thread t(func, s);
上面这张值传参方式存在多次string复制行为,使用引用传参可以减少一次复制行为,如下:
void func(string &str) { cout << str << endl; }
...
string s = "hello";
thread t(func, s);
但是上面这段代码仍然不是真正的引用传参,thread构造函数里的参数总是使用值传参。
也就是说如果在func里修改str,是不会影响到字符串s的。
处理方式是使用std::ref,实现真正的引用传参
void func(string &str);
...
string s = "hello";
thread t(func, std:;ref(s));
将指针作为参数传入
上面使用std::ref的例子也可以用指针传参实现,但是会让子线程和父线程有内存共享,会导致数据争用(data racing)
std::move
c++里很多类型的对象不支持复制,只能“移动”,例如thread对象就是可移动不可复制
thread t1(func);
// thread t2 = t1; // 错误!
thread t2 = std::move(t1); // 这时t1对象已经不能使用了
最多可以启动的线程数maxnum
当开启超过maxnum的线程时,效率不会提高反而会降低,因为这时cpu会进行上下文切换
用std::thread::hardware_concurrency()查看支持的最大线程数
c++11多线程记录2:线程管理的更多相关文章
- c++11多线程记录0
两种并发编程模型 多进程 进程间通信常用的几种方式: 文件 管道 消息队列 多线程 一个进程中存在的多个线程,通常通过共享内存来通信,(说的非常非常粗俗,就是通过类似"全局变量"的 ...
- c++11多线程记录6:条件变量(condition variables)
https://www.youtube.com/watch?v=13dFggo4t_I视频地址 实例1 考虑这样一个场景:存在一个全局队列deque,线程A向deque中推入数据(写),线程B从deq ...
- c++11多线程记录5: Unique Lock和延时初始化
https://www.youtube.com/user/BoQianTheProgrammer 视频网址 Unique Lock unique_lock和lock_guard类似,都是mutex的w ...
- c++11多线程记录4:死锁
简单示例 举个例子,桌上有一支笔和一张纸,小A和小B都要拿到纸笔写字 小A拿了笔,小B拿了纸,这时就形成了死锁(两人都不愿意让出纸笔). 其实只要稍加控制就可以避免这种情况:规定必须先拿到纸再能去尝试 ...
- c++11多线程记录3: 数据争用和Mutex的使用
https://www.youtube.com/watch?v=3ZxZPeXPaM4 学习视频 数据争用 简单来说就是存在多个线程同时对某个共同的对象进行读写(至少有一个线程在做写操作),造成读取这 ...
- c++11多线程记录1 -- std::thread
启动一个线程 话不多说,直接上代码 void func(); int main() { std::thread t(func); //这里就开始启动线程了 t.join(); // 必须调用join或 ...
- c++11の简单线程管理
1.简单的例子 #include "stdafx.h" #include <iostream> #include <thread> void functio ...
- C++ 11 多线程--线程管理
说到多线程编程,那么就不得不提并行和并发,多线程是实现并发(并行)的一种手段.并行是指两个或多个独立的操作同时进行.注意这里是同时进行,区别于并发,在一个时间段内执行多个操作.在单核时代,多个线程是并 ...
- (转)C++ 11 多线程--线程管理
说到多线程编程,那么就不得不提并行和并发,多线程是实现并发(并行)的一种手段.并行是指两个或多个独立的操作同时进行.注意这里是同时进行,区别于并发,在一个时间段内执行多个操作.在单核时代,多个线程是并 ...
随机推荐
- js replace(a,b)替换指定字符
var a="aaabbb" a= a.replace("aaa", "ccc") console.log(a) //a ="c ...
- Hibernate的批量查询——原生sql查询
1.查询所有的学生信息: (1)查询结果中,一条信息放入到一个数组中,从list集合中取出数组,并对数组进行遍历. public class GeneratorTest { public static ...
- [RN] React Native 分享弹窗 ShareAlertDialog
React Native 分享弹窗 ShareAlertDialog ShareAlertDialog.js文件 /** * 分享弹窗 */ import React, {Component} fro ...
- Goldbach’s Conjecture(信息学奥赛一本通 1622)
[题目描述] 原题来自:Ulm Local,题面详见:POJ 2262 哥德巴赫猜想:任何大于 44 的偶数都可以拆成两个奇素数之和. 比如: 8=3+5 20=3+17=7+13 42=5+37=1 ...
- c语言用指针定义一个类型进行输入输出
1 整型数组 // #include "stdafx.h" #include "stdlib.h" int _tmain(int argc, _TCHAR* a ...
- java并发编程(四) 线程池 & 任务执行、终止源码分析
参考文档 线程池任务执行全过程:https://blog.csdn.net/wojiaolinaaa/article/details/51345789 线程池中断:https://www.cnblog ...
- tomcat中文乱码
1. https://blog.csdn.net/qq_35038153/article/details/78430359 2. 1.修改apache-tomcat-9.0.14-windows-x6 ...
- java判断指定路径文件夹是否存在,若不存在则创建新的文件夹
File file = new File(dirPath); if (!file.exists()) { file.mkdirs(); }
- ethtool 强制设置网卡运行模式为100M
ethtool -s eth0 autoneg off speed 100 duplex full
- PHP 命令行参数解析工具类
<?php/** * 命令行参数解析工具类 * @author guolinchao * @email luoyecb@163.com */class CommandLine{ // store ...