Home Forums C Programming threads Win32 <-> Linux Reply To: threads Win32 <-> Linux

#3387
Priyansh Agrawal
Participant

Ok, I found the problem/solution but I’m not satisfied: All works fine when the optimizations in gcc are turned off.
Each optimization (O, O1, O2, O3, Os) will cause an endless loop.

Here an example:

#include 
#include

int wait1,wait2;

void *mythread(void *ptr)
{
int *parm;
int i;

parm=(int *)ptr;

for (i=0;i<10;i++)
{
// branch for thread no 1
if (parm[0])
{
printf("nLoop %in",i);
printf("Thread 1 started and waiting for thread 2 ...n");
wait2=0;
while (wait1);
wait1=1;

printf("Thread 1 resumed.n");
}
// branch for thread no 2
else
{
while (wait2);
wait2=1;
printf("Thread 2 started and telling Thread 1 to resume ...n");
wait1=0;
}
}

return NULL;
}

int main()
{
pthread_t thr1,thr2;
int parm1[1],parm2[1];

wait1=1;
wait2=1;
parm1[0]=1;
parm2[0]=0;

pthread_create(&thr1,NULL,mythread,(void *)parm1);
pthread_create(&thr2,NULL,mythread,(void *)parm2);

pthread_join(thr1,NULL);
pthread_join(thr2,NULL);

return 0;
}