Good afternoon, the problem is to build a multi-threaded computation and specifically that the necessary parameter i needs to be passed to each stream from an array of threads of dimension n at each iteration of k ;
//n = чему - то; int k; for(k= 0; k< K; k++) { pthread_t threads[n]; double* res[n]; int i; for(i=0; i<n; i++) { struct info inft = {.parameter = i, .result = &res[i]}; // составление структуры для треда pthread_create( &threads[i], NULL, calculate, (void*)&inft ); } //ожидание закрытия треда и суммируем полученный резалт double result = 0; for(i=0; i<n; i++) { pthread_join( threads[i], NULL); result += res[i]; } } the thread function looks like this:
void* calculate (void* args) { struct info myinf = (struct info)&args; int i_current = myinf->parameter; printf("start with %d", i_current); double result = 0; result = somefunc(myinf->result, i_current);// что то делаем *(myinf->result)= result; printf("finish with %f", result); } I expected that each stream will be given its own i and for each stream there will be a different result. But in the end, at each iteration, i - in the streams the same values
k = 1, n = 3 start with 2 finish with 66666 start with 2 start with 2 finish with 66666 finish with 66666
I tried a lot (locks, sending by reference, etc.) but it does not work as it should. Are there any ideas?