Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* t2.c
- synchronize threads through mutex and conditional variable
- To compile use: gcc -o t2 t2.c -lpthread
- SLMAAN ALBEADY
- 3.2.2 Conditional Variable
- */
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define RED "\x1B[31m" //just color for a new word "again"
- #define RESET "\x1B[0m"
- void hello(); // define two routines called by threads
- void world();
- void again(); //new*/ theard
- /* global variable shared by threads */
- pthread_mutex_t mutex; // mutex
- pthread_cond_t done_hello , done_world ; // conditional variable //new*/ done for second word
- int done = 0; // testing variable
- int main (int argc, char *argv[]){
- pthread_t tid_hello, // thread id
- tid_world,
- tid_again; //new*/
- /* initialization on mutex and cond variable */
- pthread_mutex_init(&mutex, NULL);
- pthread_cond_init(&done_hello, NULL);
- pthread_cond_init(&done_world, NULL); //new*/ to enter a new thread
- pthread_create(&tid_hello, NULL, (void*)&hello, NULL); //thread creation
- pthread_create(&tid_world, NULL, (void*)&world, NULL); //thread creation
- pthread_create(&tid_again, NULL, (void*)&again, NULL); //new*/ thread creation again
- /* main waits for the two threads to finish */
- pthread_join(tid_hello, NULL);
- pthread_join(tid_world, NULL);
- pthread_join(tid_again, NULL); //new*/
- printf("\n");
- return 0;
- }
- void hello() {
- pthread_mutex_lock (&mutex);
- printf ("Hello ");
- fflush (stdout); // flush buffer to allow instant print out
- done = 1;
- pthread_cond_signal (&done_hello); // signal world() thread
- pthread_mutex_unlock(&mutex); // unlocks mutex to allow world to print
- return ;
- }
- void world() {
- pthread_mutex_lock(&mutex);
- /* world thread waits until done == 1. */
- while(done == 0) {
- pthread_cond_wait (&done_hello, &mutex);
- }
- printf ("World");
- fflush (stdout);
- usleep(1);
- done=2; //new*/ to wait a world finish
- pthread_cond_signal (&done_world); //new*/
- pthread_cond_broadcast (&done_hello); //new*/ unblock all threads currently blocked on the specified condition variable cond.
- pthread_mutex_unlock (&mutex); // unlocks mutex
- return ;
- }
- //| ALL NEW : new thread for print therd word "Again" |*/
- void again(){
- pthread_mutex_lock(&mutex);
- /* again thread waits until done == 2. */
- while(done == 0) {
- pthread_cond_wait(&done_hello, &mutex);
- }
- while(done == 1) {
- pthread_cond_wait(&done_world, &mutex);
- usleep(1);
- }
- printf (RED" Again!"RESET);
- fflush (stdout);
- pthread_mutex_unlock(&mutex); // unlocks mutex
- return ; //NULL
- }
- /*
- salbeady@penguin:~/os$ gcc -o t2 t2.c -lpthread
- salbeady@penguin:~/os$ ./t2
- Hello World Again!
- salbeady@penguin:~/os$ ./t2
- Hello World Again!
- */
Advertisement
Add Comment
Please, Sign In to add comment