Windows |
UNIX: Linux, Mac OS X | My porthread library, osl/porthread.h |
|
Create a Thread |
CreateThread(...) (example) |
pthread_create(&th,0,fn,arg) (example) | porthread th=porthread_create(fn,arg); |
Wait for a Thread to Finish |
WaitForSingleObject(th,INFINITE) |
pthread_join(th,0); | porthread_wait(th); |
Create a Lock |
InitializeCriticalSection |
pthread_mutex_init |
porlock lk; |
Lock the lock |
EnterCriticalSection |
pthread_mutex_lock |
lk.lock(); |
Unlock the lock |
LeaveCriticalSection |
pthread_mutex_unlock |
lk.unlock(); |
Delete the lock |
DeleteCriticalSection |
pthread_mutex_destroy |
(delete variable lk) |
int shared=0;If two threads try to call "inc" repeatedly, the two executions might interleave like this:
void inc(void) {
int i=shared;
i++;
shared=i;
}
Thread A |
Thread B |
int i=shared; // i==0 i++; // i==1 // hit interrupt. switch to B shared=i; // i is still 1, so shared==1! |
int i=shared; // i==0 (again) i++; //i==1 shared=i; // shared==1 int i=shared; // i==1 i++; //i==2 shared=i; // shared==2 int i=shared; // i==2 i++; //i==3 shared=i; // shared==3 // hit interrupt, switch back to A |
int shared=0;
porlock lk; /* lock for "shared" */
void inc(void) {
lk.lock(); /* now we have exclusive access */
int i=shared;
i++;
shared=i;
lk.unlock(); /* give other threads a chance */
}