Home › Forums › C Programming › threads Win32 <-> Linux
- This topic has 1 reply, 1 voice, and was last updated 16 years, 7 months ago by Priyansh Agrawal.
- AuthorPosts
- April 28, 2008 at 8:09 am #2098Priyansh AgrawalParticipant
Hi,
I’ve got a problem in porting a multi-thread-c-programm from Win32 to Linux. On both OS there are very similar functions to create threads.
I use _beginthread in Win32 (process.h) and pthread_create in Linux (pthread.h).Normaly both functions work fine in both OS – except for one thing: I have to sync the child-thread with the main-program. So both functions/threads get the same pointer to a status variable which tells them whether to wait or to run.
In Win32 this works fine. The same code in Linux produces an endless loop.
The child-thread has something like: while(*status == 0);
“status” is a pointer to an integer.
I know, normally this IS an endless loop. But NOT when the other process changes the value of this variable.The pointers in both processes point exactly to the same address. In Win32 this loop recognizes when the value has changed. But not in Linux ???!!!
I don’t understand this behaviour at all.
Ahh, I found out something weird:
When the program produces output on the console, the Linux-code works, too.
But I don’t want to produce console-output in this loop!Could anybody help?
- April 29, 2008 at 11:15 am #3387Priyansh AgrawalParticipant
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:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#include <br />#include <br /><br />int wait1,wait2;<br /><br />void *mythread(void *ptr)<br />{<br />int *parm;<br />int i;<br /><br />parm=(int *)ptr;<br /><br />for (i=0;i<10;i++)<br />{<br />// branch for thread no 1<br />if (parm[0])<br />{<br />printf("nLoop %in",i);<br />printf("Thread 1 started and waiting for thread 2 ...n");<br />wait2=0;<br />while (wait1);<br />wait1=1;<br /><br />printf("Thread 1 resumed.n");<br />}<br />// branch for thread no 2<br />else<br />{<br />while (wait2);<br />wait2=1;<br />printf("Thread 2 started and telling Thread 1 to resume ...n");<br />wait1=0;<br />}<br />}<br /><br />return NULL;<br />}<br /><br />int main()<br />{<br />pthread_t thr1,thr2;<br />int parm1[1],parm2[1];<br /><br />wait1=1;<br />wait2=1;<br />parm1[0]=1;<br />parm2[0]=0;<br /><br />pthread_create(&thr1,NULL,mythread,(void *)parm1);<br />pthread_create(&thr2,NULL,mythread,(void *)parm2);<br /><br />pthread_join(thr1,NULL);<br />pthread_join(thr2,NULL);<br /><br />return 0;<br />}
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.