//Dr. Ramsey Fall 2007 - edits Fall 2009 #include #include //You must also compile with -lpthread. For example: //g++ sem.cpp -o sem -lpthread #include using namespace std; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t mutexattr; //pthread_mutex_init(&, &mutexattr); // _destroy // lock, unlock, trylock //the last 4 are &m as arguments sem_t sem; //sem_init (&sem, PTHREAD_PROCESS_PRIVATE,5); //sem_destroy, post, wait , trywait, getvalue //asynch safe (okay in signal handlers) //sem_Wait can be interrupted (returns 0 on success), always do: // while(!sem_wait()); void handler(int s) { cout << "SOMEONE SENT ME SIGINT!!" << endl; return; } int main() { signal(SIGINT, handler); pthread_mutex_init(&m, &mutexattr); const int semcount = 5; sem_init(&sem,PTHREAD_PROCESS_PRIVATE,semcount); int value; //initial value of sem is? sem_getvalue(&sem,&value); cout << value << endl; int result = sem_wait(&sem); //this can be interrupted //usually put sem_wait in a loop - see above comments if(result != 0) { cout << "Wait got interrupted" << endl; exit(0); //typically this is a very brutal solution to a failed wait // since processes get preempted with interrupts all the time. } /* //to show the interruptable nature, use the following: sem_wait(&sem); //3 left sem_wait(&sem); //2 left sem_wait(&sem); // 1 left sem_wait(&sem); // 0 left sem_getvalue(&sem,&value); cout << value << endl; cout <<" ********** blocking wait*********" << endl; result = sem_wait(&sem); //-1? if(result != 0) { cout << "interrupted!" << endl; } */ sem_getvalue(&sem,&value); cout << value << endl; result = sem_post(&sem); sem_getvalue(&sem,&value); cout << value << endl; cout << "Waiting for lock" << endl; pthread_mutex_lock(&m); //altho this does not solve critical section cout << "Critical section" << endl; pthread_mutex_unlock(&m); cout << "Remainder section" << endl; /* //to show the uninteruptable nature, use the following cout << "Waiting for lock...x2" << endl; pthread_mutex_lock(&m); cout << "Got the lock - can I get it again?" << endl; cout <<" ********** blocking wait*********" << endl; pthread_mutex_lock(&m); cout << "Critical section" << endl; pthread_mutex_unlock(&m); cout << "Remainder section" << endl; */ }