2016-10-03 65 views
1

我写了下面的代码,但是当我运行它时,它带来了段错误。它虽然编译正确。我的错误在哪里?线程段错误

#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; 
} 

任何暗示都欢迎。

谢谢

回答

2

你有serveral的问题:

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(),以便只有主线程退出和其他线程继续。