c++11多线程内存错误

c++11 multithreading memory error

本文关键字:错误 内存 多线程 c++11      更新时间:2023-10-16

我有以下代码:

somefunc(string s, semaphore* sem) { 
     //some functionality
     sem->signal();
}
int main() {
    int num = 0;
    semaphore sem(0);
    vector<string> arr;
    for (string& s : arr) {
        ++num; 
        thread(somefunc, s, &sem).detach();
    }
    for (int i = 0; i < num; i++)
        sem.wait();
}

我在thread()所在的行上的std::string分配中收到SIGSEGV错误。这个代码有问题吗?semaphore是一个使用互斥和条件变量的自定义类。

如果没有看到真实的代码,很难判断,但我的猜测是,当字符串引用s被复制到thread中时,它不再有效,因为主线程已经退出了包含arr的作用域。

在valgrind或类似的内存检查器下运行代码应该有助于诊断问题。