Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22113

Linux multithread(Pthread-C++) adding 0~99 has different result with/without sleep

$
0
0

I used 10 Pthreads to add up 0~9,10~19,20~29,30~39,40~49,50~59,60~69,70~79,80~89,90~99 and

for(i=0;i<10;i++)
{
   temp=i;
   temp+=1;
   temp*=10;
   point_i=&temp;
   pthread_create(&tid[i],NULL,thread_sum,point_i);
   //sleep(0.5);
}

At this part of code( temp is just to give an argument to thread_sum function for each thread to calculate 0~9 11~19 ...) and my thread_sum receives 10, 20, 30 and does for(i=10-10;i<10;i++) sum+=i;for(i=20-10;i<20;i++) sum+=i;for(i=30-10;i<30;i++) sum+=i;for(i=40-10;i<40;i++) sum+=i; and so on. for each thread. I wrote it using

for(i=x-10;i<x;i++)sum+=i;

What I found is that without the sleep(0.5) when creating, all threads add up 90~99 but with sleep(0.5), it calculates as I thought. 0~9 is added 10~19 is added 20~29 is added and so on. I am not sure why this happens. Thank you for somebody who could resolve my horrible problem ㅜ.ㅜ

A code I wrote


Viewing all articles
Browse latest Browse all 22113

Trending Articles