【发布时间】:2020-02-05 08:08:20
【问题描述】:
#define SIZE 3
#define MAX_THREADS 9
int main() {
...
pthread_t m_threads[MAX_THREADS];
int t_num = 0;
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
...
pthread_create(&m_threads[i], NULL, multiply, (void *) &td[t_num]);
t_num++;
}
}
for( int i = 0; i < MAX_THREADS; i++ ) {
pthread_join(m_threads[i], NULL);
}
return 0;
}
我正在创建 9 个线程来做一些矩阵乘法。计算成功。但是当我尝试加入线程时程序崩溃了。在 for 循环的第 4 次迭代期间,程序在执行 pthread_join(m_threads[i], NULL) 时崩溃。
调试程序我从 GDB 得到这个分段错误。
Thread 1 "Pthread" received signal SIGSEGV, Segmentation fault.
0x00007f7d0063ac9f in __free_tcb () from /lib/x86_64-linux-gnu/libpthread.so.0
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
【问题讨论】:
-
您正在使用
m_threads数组的未初始化元素,就像它们是有效的一样。 -
你的意思是
pthread_create(&m_threads[t_num],而不是pthread_create(&m_threads[i]? -
pthread_create(&m_threads[i]应该是pthread_create(&m_threads[t_num] -
@AlanBirtles 和其他人。谢谢您的帮助。对我来说这是多么愚蠢的错误。
-
如果 MAX_THREADS > SIZE*SIZE 怎么办?你能加入一个尚未启动的线程吗?
标签: c++ segmentation-fault pthreads