我是韩国人,我不擅长英语,但如果你给我一个评论
我会很高兴并会尝试理解它。
例如,我创建了 10 个线程,并尝试在创建后加入它们并返回值。
但是当我加入最后一个线程时,出现了段错误。
结果是这样的..
Before Thread 1 create
After Thread 1 create
Before Thread 0 create
After Thread 0 create
Before Thread 1 join
After Thread 1 join
Before Thread 0 join
Segmentation Fault(core dumped)
当我创建 4 个线程时,它就像
Before Thread 3 create
After Thread 3 create
Before Thread 2 create
After Thread 2 create
Before Thread 1 create
After Thread 1 create
Before Thread 0 create
After Thread 0 create
Before Thread 3 join
After Thread 3 join
Before Thread 2 join
After Thread 2 join
Before Thread 1 join
After Thread 1 join
Before Thread 0 join
Segmentation Fault(core dumped)
我似乎找不到原因。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex_lock;
struct arg_struct {
int a;
int b;
};
void *t_function(void *data) {
pthread_mutex_lock(&mutex_lock);
struct arg_struct *arg = (struct arg_struct *)data;
long int s;
s = arg->a;
pthread_mutex_unlock(&mutex_lock);
return (void **)s;
}
int main()
{
int i;
pthread_t p_thread[2];
int thr_id;
int status;
struct arg_struct arg[2];
for(i = 1; i >= 0; i--) {
arg[i].a = i;
arg[i].b = i;
}
pthread_mutex_init(&mutex_lock, NULL);
for(i = 1; i >= 0; i--) {
printf("Before Thread %d create\n", i);
thr_id = pthread_create(&p_thread[i],NULL, t_function, (void *)&arg[i]);
printf("After Thread %d create\n", i);
usleep(1000);
}
int temp[2];
for(i = 1; i >= 0; i--) {
printf("Before Thread %d join\n", i);
pthread_join(p_thread[i], (void**)&status);
printf("After Thread %d join\n", i);
temp[i] = status;
}i
printf("%d%d", temp[1], temp[0]);
pthread_mutex_destroy(&mutex_lock);
return 0;
}
最佳答案
pthread_t p_thread[2];
struct arg_struct arg[2];
int temp[2];
你在这里只为两个元素分配了空间,所以如果你启动超过 2 个线程,你将跑到数组的末尾,并可能崩溃或破坏堆栈。
另外:
pthread_join(p_thread[i], (void**)&status);
status
是一个int
,而不是一个void *
;尝试这样做将尝试将 void *
存储在 int
中。在许多 64 位平台上,这也会溢出(因为 void *
将是 8 个字节,而 int
是 4 个字节)。将 status
设为 void *
,并停止尝试像这样消除编译器错误。它们是有原因的错误。
关于c - pthread(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8018272/