Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用std::map和std::thread时出现意外行为_C++_Multithreading_C++11_Stl - Fatal编程技术网

C++ 使用std::map和std::thread时出现意外行为

C++ 使用std::map和std::thread时出现意外行为,c++,multithreading,c++11,stl,C++,Multithreading,C++11,Stl,因此,我需要为我的应用程序创建一个线程池,这使我创建了一个std::map对象。 我遇到了一些非常意外的行为,可以简化为: std::映射线程; threads.insert(std::pair(1,std::thread([])){ 标准::cout来自: 如果容器中尚未包含具有等效键的元素,则将元素插入容器中 您的映射已经在键1处包含一个元素,因此第二个线程。insert不起任何作用。您只需尝试在同一std::thread上加入两次。这就是线程的原因。擦除(1);解决了问题,您的映射不再在键

因此,我需要为我的应用程序创建一个线程池,这使我创建了一个
std::map
对象。 我遇到了一些非常意外的行为,可以简化为:

std::映射线程;
threads.insert(std::pair(1,std::thread([])){
标准::cout来自:

如果容器中尚未包含具有等效键的元素,则将元素插入容器中

您的映射已经在键
1
处包含一个元素,因此第二个
线程。insert
不起任何作用。您只需尝试在同一
std::thread
上加入两次。这就是
线程的原因。擦除(1);
解决了问题,您的映射不再在键
1
处包含线程

如果容器中尚未包含具有等效键的元素,则将元素插入容器中


您的映射已在键
1
处包含一个元素,因此第二个
线程。insert
不起任何作用。您只是尝试在同一
std::thread
上加入两次。这就是
线程的原因。擦除(1)
解决了这个问题,当你在stdout上跟踪时,你的地图不再在键
1

上包含线程,不要忘记刷新。@molbdnilo-换行符应该这样做。@OliverCharlesworth
'\n'
不刷新
std::cout
@FrançoisAndrieux-这对我来说是新闻:/(至少在cout在典型环境中包装标准件的情况下是如此。)你能澄清一下吗?@OliverCharlesworth:
\n
会导致
std::cout
刷新,如果它直接连接到终端,则不会。当你在stdout上进行跟踪时,不要忘了刷新。@molbdnilo-换行应该这样做。@OliverCharlesworth
'\n'
不会刷新
std::cout
@FrançoisAndrieux-那是news-to-me:/(至少在cout在典型环境中封装stdout的情况下是如此。)你能澄清一下吗?@OliverCharlesworth:
\n
如果它直接连接到终端,会导致
std::cout
刷新,但其他情况下不会。太好了,谢谢。所以没有直接的API来覆盖现有的密钥,对吗?@OmerPerry
treads[1]=std::thread([](){/*dowork*/});
将“覆盖”键
1
处的线程使用一个新的线程。在单个调用中没有删除然后替换元素的方法,但是移动赋值对任何可移动类型都应该做同样的事情。太好了,谢谢。因此没有直接的API来覆盖现有键,对吗?@OmerPerry
treads[1]=std::thread([]){/*do work*/});
将用一个新的线程“覆盖”键
1
处的线程。在单个调用中没有删除然后替换元素的方法,但是移动赋值应该对任何可移动类型执行相同的操作。
I'm the first thread and I'm gonna work
Thread 1 joinable? 0
threads.erase(1);