-
Mutex in C
Hello all,
I'm having a problem locking a resource in a DLL. There are concurrent threads accessing my library, and I need to lock and set a global variable the moment the first thread accesses a certain function. The problem is that evey method I have tried fails to set the mutex lock before other threads have read the mutex condition.
One method I tried was to simply use a global, boolen flag, initalize it to 0, and check to see if it is 0 upon entry to the function. So, in theory, if thread_1 hits the function, it would find the flag set to false, set it to true, do what it needs to do, and set it back to false. But what actually happend is that thread_1 finds that the flag is false, and before it sets it to true, thread_2 through thread_15 also find that it is false. The result is that 15 threads are accessing the same resource simutaneously.
I have also tried starting the function off with a while loop with the condition that while the flag is true loop. The next statement sets the flag to true if it is false. Again, in theory, the loop condition should be skipped by thread_1, and the global flag should then be set to true, thus causing all subsequent threads to wait in the loop. But the problem here is the same: by the time thread_1 sets the flag to true, the threads on its heels have passed the while loop.
I'm sure that I need to use lower level C calls than the ones I have been using, but I can't seem to find any information that is OS independant. (For example, I have read about pthread on Solaris, but I'm currently on Windows, and I will also need to port to AIX). Any ideas?
-
-
> but I can't seem to find any information that is OS independant.
That's because there isn't anything.
Standard C doesn't know about processes or threads.
> Any ideas?
Create a file called porting.c which contains functions you desire, and which are easy to port to your anticipated operating systems.
At least then, for each function you need, you only need to edit one file in one place.
-
Read and digest this you may find it helpful.
-
Well, it won't be the first time Schmidt has been busted:
http://www.cs.umd.edu/~pugh/java/mem...edLocking.html
Even though that's primarily in Java, it's broken in C/C++ for the same reasons.
DCL can be implemented correctly in Win32, but you really need to know what you're doing:
http://www.microsoft.com/whdc/driver...MP_issues.mspx
jgs - I highly recomend that you simply protect access to your resource with a critical section.
gg