120 likes | 134 Views
This review covers user threads, calling special library functions, thread.h and thread library, fast switching, limitations, creating pthreads, C++11 threads, C++11 mutex, semaphore.h, coding semaphores, and more examples.
E N D
cosc 4740 Implementing Threads & Semaphores
Review • User Thread • Call special library functions • thread.h and thread library • Fast switching: switching among peer threads does not incur an interrupt to the kernel • No short-term scheduler, no address change • Only PC & stack-address changed. • Limitations • Schedulers view a process, not threads of a process
Creating pthreads We are not using the method anymore, but you should see it #include <pthread.h> • The subroutine to be called, must be a void * and have a void * parameter void * subroutine(void * parameter) { } • To create the threads in mail main () { pthread_t th1; //declare thread variable // start thread with subroutine call pthread_create(&th1, NULL, subroutine, 0); // wait for thread to finish before main program exits. pthread_join(th1, 0); }
Creating pthreads • To compile on linux • g++ file.c –lpthread -lpthread includes the thread object code. • Shown on linux with oddeven.cpp g++ oddeven.cc –lpthread –o oddeven
C++11 threads #include <thread.> • The subroutine to be called, must be a void • It can have parameters that are call by value only or no parameters. void sub1(int parameter) { … } void sub2() { … } main () { thread th1, th2; //declare thread variable inti=1; //parameter variable // start thread with subroutine call th1 = thread(sub1, i); th2 = thread(sub2); // wait for thread to finish before main program exits. th1.join(); th2.join(); }
C++11 threads • To compile on linux • g++ file.cpp –pthread -std=c++11 -pthread includes the thread object code.
C++11 mutex • #include <mutex> • always init'd to 1 (unlocked) mutexmylock; mylock.lock(); • Critical region mylock.unlock(); //can't go above 1.
semaphore.h • We are going to use three main method • sem_init • initialized the semaphore to the value. • sem_wait • which is the wait method • sem_post • which is the signal method http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/semaphore.h.html
Coding semaphores • your semaphores need to be global variable so all the threads can use it. sem_t sem2; • init semaphore sem1 to 1. The second parameter will always be 0 for our code. sem_init(&sem1,0,1); • Wait method sem_wait( &sem2 ); • Signal method sem_post( &sem2 );
Using oddeven program with semaphores, so that it prints odd, even, odd, even, … • Shown on linux with oddevens.cc g++ semaphore_mutex_oddeven.cpp -pthread -std=c++11 -o oddeven
More Examples • buffer examples • solutions for the producer consumer problem • with semaphores and mutex • They take cmd line parameters for how many producers and consumers. (no parameters defaults to 1 of each) • unisex is a semaphore solution to unisex bathroom problem.
Q A &