【发布时间】:2020-12-26 07:13:31
【问题描述】:
我正在尝试运行下面的代码,该代码使用 pthread_create 创建一个线程,并从线程内部返回计数。代码给了我一个分段错误
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void *test_routine(void *arg);
int main(int argc, char **argv)
{
pthread_t first_thread;
void *thread_return;
int result = 0;
result = pthread_create(&first_thread, NULL, test_routine, NULL);
if (0 != result)
{
fprintf(stderr, "Failed to create thread %s\n", strerror(result));
exit(1);
}
result = pthread_join(first_thread, &thread_return);
if (0 != result) {
fprintf(stderr, "Failed to join a thread: %s\n", strerror(result));
pthread_exit(NULL);
}
printf("\nValue returning from the test routine %d\n", (int) thread_return);
free(thread_return);
exit(3);
}
void *test_routine(void *arg)
{
int count = 0;
count++;
pthread_exit(count);
}
【问题讨论】:
标签: c pthreads posix pthread-join