Please review this tutorial to Linux Pthread.. Note the following (taken from manual page of pthread_create):
#include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); Compile and link with -pthread.Note that you need to compile your program using the -pthread option:
g++ myprog.cpp -lpthreadRequirement
You can choose to work on one of the following:
class barrier{ public: barrier (int n); //initialize barrier to be used for n threads /* for the first n-1 threads that call checkin, they will be put on hold, i.e., waiting mode, and only being worken up when the last (n-th) thread call checkin. When the n-th thread calls checkin(), all threads returned from checkin(). The same behavior repeats for subsequent calls to checkin()... This means the barrier can be used for multiple times. */ void checkin(); private: // Introduce state variables as necessary ... //intrudoce synchronization variables such as mutex and conditional variables // as necessary }; //main() for testing barrier class const int THREAD_NUM=10; barrier br(THREAD_NUM); //a global variable shared by all threads void * ThreadRoutine (void * param) { // phase 1 sleep: sleep for some random number of seconds (between 1 and 10 seconds) cout << "finishing phase1, checking-in... !\n"; br.checkin(); // phase 2 sleep: sleep for random number of seconds, different from above (between 1 and 10 seconds) cout << "finishing phase2, checking-in... !\n"; br.checkin(); // phase 3 sleep: sleep for some random number of seconds (between 1 and 10 seconds) cout << "finishing phase3, checking-in... !\n"; br.checkin(); cout << "done!\n"; } int main() { 1. create THREAD_NUM threads, passing ThreadRoutine as their start routine 2. calling pthread_join to wait for all to finish. }
class PriorityLock{ public: // call this to enter the critical section. // if no thread is in critical section, calling thread is allowed in; // otherwise, it will be put in waiting... void enter (int priority_level); // thread call this when it finishes its critical section. // if there are more than one threads waiting, the one with highest priority // is allowed in. void exit(); private: // figure out this ... }; //main for testing PriorityLock void * ThreadRoutine (void * param) { int priority_level = (int) param; cout <<"Thread "<< priority_level << " calling enter \n"; lock.enter (priority_level); //sleep for some random amount of time lock.exit(); } int main() { 1. Creating 10 threads with priority level from 0,1,...9 (i.s., passing this value to the ThreadRoutine) 2. calling pthread_join to wait for all thread to finish... }
Submission
Please submit your program, named lab3.cpp, using submit3595 script:
submit3595 LAB4 lab4.cppTo verify:
verify3595 LAB4 lab4.cpp