Professional Documents
Culture Documents
Simple Demo Using Threads and Semaphores
Simple Demo Using Threads and Semaphores
Simple Demo Using Threads and Semaphores
//-------------------------------------------------------------------------
// 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