41 lines
		
	
	
		
			934 B
		
	
	
	
		
			C
		
	
	
	
	
	
			
		
		
	
	
			41 lines
		
	
	
		
			934 B
		
	
	
	
		
			C
		
	
	
	
	
	
| #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;
 | ||
| }
 |