Simple demo using threads and semaphores:
o Everything in one file: main.C
//-------------------------------------------------------------------------
// Simple program that creates two new threads. The main thread waits
for
// completion of the other two. The new threads share a semaphore and
one
// thread does a P (sem_wait) and the other a V (sem_post).
// Compile with: g++ -Wall -pedantic sync-demo.C -lrt -lpthread
//----------------------------------------------------------------------
---
#include
#include
#include
#include
sem_t sem;
void *
ThreadA (void *p) {
cerr << "Thread A: entering" << endl;
int rv = sem_wait (&sem);
cerr << "Thread A: exiting" << endl;
return 0;
}
void *
ThreadB (void *p) {
cerr << "Thread B: entering" << endl;
int rv = sem_post (&sem);
cerr << "Thread B: exiting" << endl;
return 0;
}
void
CheckRV (int rv, char *msg) {
if (rv) {
cerr << msg << rv << endl;
perror ("perror says: ");
exit (-1);
}
return;
}
int
main (int argc, char *argv[])
{
int rv;
void *retval=0;
pthread_t thread1;
pthread_t thread2;
//----Initialize semaphore to 0
rv = sem_init (&sem, 0, 0);
CheckRV (rv, "Main: Error in creating Semaphore sem, rv=");
//----Create threads
cerr << "Main: Creating Thread A." << endl;
rv = pthread_create (&thread1, NULL, ThreadA, NULL);
CheckRV (rv, "Main: Error in creating Thread A, rv=");
cerr << "Main: Creating Thread B." << endl;
rv = pthread_create (&thread2, NULL, ThreadB, NULL);
CheckRV (rv, "Main: Error in creating Thread B, rv=");
rv = pthread_join (thread1, &retval);
CheckRV (rv, "Main: Error in joining with Thread A, thread
retval=");
rv = pthread_join (thread2, &retval);
CheckRV (rv, "Main: Error in joining with Thread B, thread
retval=");
}