来自线程的分段错误
segmentation fault from threads
我已经写了下面的代码,但是当我 运行 它带来了分段错误。它虽然编译正确。我的错误在哪里?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
int *i = (int *) arg;
char buf[123];
snprintf(buf, sizeof(buf), "thread %d", *i);
return buf;
}
int main(int argc, char *argv[]) {
int i;
pthread_t *pt = NULL;
for (i = 0; i < N; i++) {
pthread_create(pt, NULL, run, &i);
}
return EXIT_SUCCESS;
}
欢迎任何提示。
谢谢
您有几个问题:
1) 您将 NULL 传递给 pthread_create()
,这可能是段错误的原因。
2) 您不需要等待线程完成(当 main
线程退出时,整个进程都会死亡)。
3) 您正在将地址相同的变量 i
传递给所有线程。这是一场数据竞赛。
4) 您正在从线程函数返回局部变量 buf
的地址。
您可以像这样修复它:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
int *i = (int *) arg;
char *buf = malloc(16);
snprintf(buf, 16, "thread %d", *i);
return buf;
}
int main(int argc, char *argv[]) {
int i;
void *ret;
int arr[N];
pthread_t pt[N];
for (i = 0; i < N; i++) {
arr[i] = i;
pthread_create(&pt[i], NULL, run, &arr[i]);
}
for (i = 0; i < N; i++) {
pthread_join(pt[i], &ret);
printf("Thread %d returned: %s\n", i, (char*)ret);
free(ret);
}
return EXIT_SUCCESS;
}
请注意,您不需要使用 pthread_join()
调用。也可以从主线程调用pthread_exit()
,这样只有主线程退出,其他线程继续。
我已经写了下面的代码,但是当我 运行 它带来了分段错误。它虽然编译正确。我的错误在哪里?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
int *i = (int *) arg;
char buf[123];
snprintf(buf, sizeof(buf), "thread %d", *i);
return buf;
}
int main(int argc, char *argv[]) {
int i;
pthread_t *pt = NULL;
for (i = 0; i < N; i++) {
pthread_create(pt, NULL, run, &i);
}
return EXIT_SUCCESS;
}
欢迎任何提示。
谢谢
您有几个问题:
1) 您将 NULL 传递给 pthread_create()
,这可能是段错误的原因。
2) 您不需要等待线程完成(当 main
线程退出时,整个进程都会死亡)。
3) 您正在将地址相同的变量 i
传递给所有线程。这是一场数据竞赛。
4) 您正在从线程函数返回局部变量 buf
的地址。
您可以像这样修复它:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
int *i = (int *) arg;
char *buf = malloc(16);
snprintf(buf, 16, "thread %d", *i);
return buf;
}
int main(int argc, char *argv[]) {
int i;
void *ret;
int arr[N];
pthread_t pt[N];
for (i = 0; i < N; i++) {
arr[i] = i;
pthread_create(&pt[i], NULL, run, &arr[i]);
}
for (i = 0; i < N; i++) {
pthread_join(pt[i], &ret);
printf("Thread %d returned: %s\n", i, (char*)ret);
free(ret);
}
return EXIT_SUCCESS;
}
请注意,您不需要使用 pthread_join()
调用。也可以从主线程调用pthread_exit()
,这样只有主线程退出,其他线程继续。