<nd*******@zipl ip.com> skrev i en meddelelse
news:11******** *************@j 73g2000cwa.goog legroups.com...
I need a simple multi-thread/process interlock mechanism, that works on
Windows and Linux. However, they have rather different mechanisms. I
put together a system that seems to me to work, and be simple, without
any OS intervention. However, I wanted to ask if anyone saw any
possible leakage. Here it is:
static volatile int lock = 0; // Variable for lock
void controlledAcces s() // Function to control access
{
for(;;)
{
if(++lock == 1)
{
// locked section, free access to protected resource
--lock;
break;
}
else
{
--lock;
sleep(1000); // Or whatever }
}
}
Anyone see a way that two threads can get in the critical section?
That is absolutely not thread safe :)
2 or more threads could see lock == 1.
For win32 you can use critical section on a single cpu system and semaphores
on linux
the following sample is thread safe on a single cpu'ed system.
For multi cpu'ed systems win32 has functions like InterlockedIncr ement(),
InterlockedDecr ement(), InterlockedExch ange() they will make sure that
processors are instructed to force their memory caches to agree
with main memory (so we're sure both cpus see the same value of an object).
For win32 i made my own critical section, that simply uses
InterlockedEcha nge
to compare the thread id's and set the lock. You could do the same and make
it work on both platforms.
#if defined (_WIN32)
CRITICAL_SECTIO N cs;
#else
sem_t semlock;
#endif
DWORD WINAPI SomeThread(LPVO ID lpParam) {
int iTrd = (int)lpParam;
while (condition) {
#if defined (_WIN32)
EnterCriticalSe ction(&cs);
#else
while (sem_wait(&seml ock) == -1) {
if (errno != EINTR) {
// failed to lock
}
}
#endif
std::cout << "Thread " << iTrd << " says: Hello World!" <<
std::endl;
#if defined (_WIN32)
LeaveCriticalSe ction(&cs);
#else
if (sem_post(&seml ock) == -1) {
// failed to unlock
}
#endif
Sleep(200);
}
}
void main() {
#if defined (_WIN32)
InitializeCriti calSection(&cs) ;
#else
if (sem_init(&seml ock, 0, 1) == -1) {
// failed to init
}
#endif
for (int i=0; i<max_trd; i++) {
CreateThread(pa rams);
}
while (condition) {
// program main loop
}
#if defined (_WIN32)
DeleteCriticalS ection(&cs);
#else
if (sem_destroy(&s emlock) == -1) {
// failed
}
#endif
}
I hope this was any help to you :)
//eric