You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引入SDL2后因std::thread调用方式引发Segmentation fault的原因咨询

问题原因分析

首先明确:程序崩溃和SDL2无关,核心问题出在你对std::thread的内存分配方式上。

错误点详解

  • 你用malloc分配了std::thread数组:threads = (std::thread *)malloc(sizeof(std::thread) * thread_ct);
    malloc只是单纯分配裸内存,不会调用std::thread的构造函数,这会导致数组里的std::thread对象处于未构造的非法状态。
  • 之后直接对threads[1]赋值:threads[1] = std::thread(pool_executor);
    这相当于对一个未初始化的std::thread对象执行赋值操作,而std::thread的赋值运算符要求左侧是合法可操作的对象,未构造的对象会直接触发未定义行为,表现为段错误。

修复方案

用C++原生的内存管理方式或容器,确保std::thread的构造函数被正确调用:

方案1:使用new数组替代malloc

#include <thread>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
void pool_executor()
{
    return;
}
class nn_thread
{
    std::thread *threads;
    int thread_count; // 保存线程数量,避免析构时出错

public:
    nn_thread(int thread_ct) : thread_count(thread_ct)
    {
        threads = new std::thread[thread_ct]; // new会调用默认构造函数初始化每个thread
        threads[1] = std::thread(pool_executor);
    }
    ~nn_thread()
    {
        if (threads[1].joinable()) { // 先检查线程是否可join,避免重复join
            threads[1].join();
        }
        delete[] threads; // 用delete[]释放new分配的数组
    }
};
int main(int argc, char *argv[])
{
    nn_thread model_threads(4);
    return 0;
}

方案2:使用std::vector更安全(推荐)

用std::vector管理线程,彻底避免手动内存管理的错误:

#include <thread>
#include <vector>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
void pool_executor()
{
    return;
}
class nn_thread
{
    std::vector<std::thread> threads;

public:
    nn_thread(int thread_ct) : threads(thread_ct) // vector会自动构造所有thread对象
    {
        threads[1] = std::thread(pool_executor);
    }
    ~nn_thread()
    {
        if (threads[1].joinable()) {
            threads[1].join();
        }
        // vector会自动析构所有线程,无需手动释放内存
    }
};
int main(int argc, char *argv[])
{
    nn_thread model_threads(4);
    return 0;
}

额外注意事项

  • 当前代码只初始化了threads[1],其他索引的线程是默认构造的(不可join),后续如果要初始化更多线程,记得每个线程都要正确join或detach。
  • 永远不要用malloc/free管理C的非平凡类型(比如std::thread、std::string这类带构造/析构函数的类型),必须用C原生的内存管理方式或容器。

内容的提问来源于stack exchange,提问作者Suryansh Dey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:52:51