gpt4 book ai didi

c++ - 将 std::thread 分配给 vector 时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:19 26 4
gpt4 key购买 nike

这个段错误:

std::vector<std::thread>    _pool;
State & _state;

...

for(uint32_t n = 0; n < nThreads; ++n)
_pool[n] = std::thread(_thFunction, std::ref(_state));

这不是:

std::vector<std::thread>    _pool;
State & _state;

...

for(uint32_t n = 0; n < nThreads; ++n)
_pool.push_back( std::thread(_thFunction, std::ref(_state)) );

对 vector 使用 push_back 而不是对 vector 中的特定条目使用赋值的区别。

_thFunction 是一个 std::function。

当我将 pool.reserve(10) 应用于第一个代码块时,我仍然在第一次赋值时遇到段错误。

我怀疑这与移动语义有关,但我不确定。这是怎么回事?

来自 gdb 的堆栈跟踪似乎表明 this 指针为空:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004092e5 in std::thread::joinable (this=0x0) at /usr/include/c++/4.8.3/thread:162
162 { return !(_M_id == id()); }
(gdb) backtrace
#0 0x00000000004092e5 in std::thread::joinable (this=0x0) at /usr/include/c++/4.8.3/thread:162
#1 0x000000000040927a in std::thread::operator=(std::thread&&) (this=0x0,
__t=<unknown type in /home/stackuser/src/dsl/build/debug/server/dsl, CU 0x0, DIE 0x37b88>)
at /usr/include/c++/4.8.3/thread:150
#2 0x000000000041350d in ThreadPool<std::function<void (State&)> >::ThreadPool(State&, unsigned int, std::function<void (State&)>) (this=0x69aed0, state=..., nThreads=2, thFunction=...)
at src/server/ThreadPool.h:38
#3 0x0000000000408405 in Application::Application (this=0x6946e0) at src/server/Application.cpp:69
#4 0x0000000000455594 in Singleton<Application>::CreateInstance () at src/server/Singleton.h:12
#5 0x0000000000454997 in main (argc=1, argv=0x7fffffffdc98) at src/server/main.cpp:85

最佳答案

阅读引用 documentation您正在使用的 operator[]

Returns a reference to the element at specified location pos. No bounds checking is performed.

因此,当您在一个空 vector 上调用 _pool[n] 时,您会得到一个对不存在的对象的引用,并且随之而来的是未定义的行为。为该引用赋值不会增加 vector 。

reserve 也不向 vector 添加任何元素。它只是增加了 vector 的容量,这意味着在达到该容量之前,将元素插入到末尾不会使元素的迭代器/引用/指针无效。

resize(n) 会在 vector 中创建 n 对象,我怀疑你希望 reserve 这样做,这是初始化的好方法当您不知道构造 vector 时的计数和值时,具有相同对象的 vector 。但是,如果您无论如何都要覆盖对象,使用 reservepush_back 会浪费更少的资源。或者,如果您知道 vector 中所需的值,则可以使用构造函数简单地填充 vector 。

关于c++ - 将 std::thread 分配给 vector<std::thread> 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com