【发布时间】:2021-06-13 14:31:33
【问题描述】:
所以我在做 C 编程作业时遇到了一个奇怪的线程行为:
我给一个线程一个值,然后它把它返回给pthread_exit() 函数,然后我在主函数中添加所有返回的值。问题是只有第一个值是完全错误的,这意味着我的转换是正确的,但是有一个内存问题,即使有帮助我也无法解决。
代码如下:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void * fonction_thread(void * arg);
long s = 0; //int to sum on
int main (int argc, char* argv[])
{
int N,i ; //N is the number of threads created
void* ret ; //returned value
N= atoi(argv[1]);
s=0;
for(i=1; i<N+1; i++){
//creation of the threads
pthread_t thr;
if (pthread_create(&thr, NULL, fonction_thread, &i) != 0) {
fprintf(stderr, "Erreur dans pthread_create\n");
exit(EXIT_FAILURE);
}
//recovering the value
pthread_join(thr, &ret);
printf("retour : %d\n\n", *((int*)ret)); //transtyping void* to int* before derefencement
s+= *((int*)ret);
}
printf("%ld\n", s);
}
//thread handler
void * fonction_thread(void * arg)
{
int n;
n = *((int *)arg); //recovering the value given by the main
printf("thread numéro %d créé\n", n);
pthread_exit((void*) &n); //casting then returning value
}
这是控制台视图: console screeshot
【问题讨论】: