qfedu-linux-advanced-level/day6/thread4.c

41 lines
934 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *thread_task(void *data)
{
int *arr = (int *)data;
int total = 0;
for (int i = arr[0]; i <= arr[1]; i++)
{
total += i;
}
int *result = malloc(sizeof(int));
*result = total;
return result;
}
int main()
{
pthread_t tid;
int arr[2] = {1, 100};
if (pthread_create(&tid, NULL, thread_task, arr) != 0)
{
perror("pthread_create");
return 1;
}
int *task_result;
// pthread_join函数等待子线程执行完毕并将子线程的返回值存储在task_result指针中。注意这里需要将task_result的类型为int*的指针的地址传递给pthread_join函数。
if (pthread_join(tid, (void **)&task_result) != 0)
{
perror("pthread_join");
return 1;
}
printf("线程返回的结果是: %d\n", *task_result);
free(task_result);
return 0;
}