英文:
Segmentation fault because of std:: thread launching through a method
问题
#include <thread>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
void pool_executor()
{
return;
}
class nn_thread
{
std::thread *threads;
public:
nn_thread(int thread_ct)
{
threads = (std::thread *)malloc(sizeof(std::thread) * thread_ct);
threads[1] = std::thread(pool_executor);
}
~nn_thread()
{
threads[1].join();
free(threads);
}
};
int main(int argc, char *argv[])
{
nn_thread model_threads(4);
return 0;
}
添加了这个图形库SDL2后,我的程序开始抛出分段错误。有人能解释一下原因吗?
我尝试搜索SDL2是否对多线程有一些限制,但我没有找到任何信息。
英文:
#include <thread>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
void pool_executor()
{
return;
}
class nn_thread
{
std::thread *threads;
public:
nn_thread(int thread_ct)
{
threads = (std::thread *)malloc(sizeof(std::thread) * thread_ct);
threads[1] = std::thread(pool_executor);
}
~nn_thread()
{
threads[1].join();
free(threads);
}
};
int main(int argc, char *argv[])
{
nn_thread model_threads(4);
return 0;
}
As soon as i add this graphic library SDL2, my program starts throwing Segmentation fault. Can someone explain me the reason?
I tried searching if SDL2 has some restrictions for multi-threading or something but i didn't find any.
答案1
得分: 1
不想让你感到太困惑,我想给你提供一个更基本的解决方案:
```cpp
#include <thread>
#include <vector>
void pool_executor()
{
return;
}
class nn_thread
{
std::vector<std::thread> threads;
public:
nn_thread(int thread_ct)
{
for (int i = 0; i < thread_ct; ++i) {
threads.emplace_back(&pool_executor);
}
}
~nn_thread()
{
for (auto& thread : threads) {
thread.join();
}
}
};
int main(int argc, char *argv[])
{
nn_thread model_threads(4);
}
在C++中,你不需要使用malloc,即使在处理SDL2时也不需要。容器是你的朋友,正如你所看到的,甚至可以用std::array
来替代那个vector,但那样的话我就必须为nn_thread
进行模板化。所以我希望这个更基本的代码能帮助你。
<details>
<summary>英文:</summary>
To not bear you to much confusion, I like to give this more basic solution to you:
#include <thread>
#include <vector>
void pool_executor()
{
return;
}
class nn_thread
{
std::vector<std::thread> threads;
public:
nn_thread(int thread_ct)
{
for (int i = 0; i < thread_ct; ++i) {
threads.emplace_back(&pool_executor);
}
}
~nn_thread()
{
for (auto& thread : threads) {
thread.join();
}
}
};
int main(int argc, char *argv[])
{
nn_thread model_threads(4);
}
In C++ you don't have to use malloc, even when dealing with the SDL2. Containers are your friends as you can see, one could even replace that vector with an `std::array` but then I would have to template `nn_thread`. So I hope this more basic code helps you.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论