c - How to specify the pthread that should be the first to get into a critical region? -


i want decide thread should enter critical region first according priority. in example below, there way choose specific thread , let enter critical region first? make step implement lottery scheduling.

/* includes */ #include <unistd.h>     /* symbolic constants */ #include <sys/types.h>  /* primitive system data types */  #include <errno.h>      /* errors */ #include <stdio.h>      /* input/output */ #include <stdlib.h>     /* general utilities */ #include <pthread.h>    /* posix threads */ #include <string.h>     /* string handling */ #include <semaphore.h>  /* semaphore */  /* prototype thread routine */ void handler ( void *ptr );  /* global vars */ /* semaphores declared global can accessed     in main() , in thread routine,    here, semaphore used mutex */ sem_t mutex; int counter; /* shared variable */  int main() {     int i[2];     pthread_t thread_a;     pthread_t thread_b;      i[0] = 0; /* argument threads */     i[1] = 1;      sem_init(&mutex, 0, 1);      /* initialize mutex 1 - binary semaphore */                                  /* second param = 0 - semaphore local */      /* note: can check if thread has been created checking return value of        pthread_create */                                      pthread_create (&thread_a, null, (void *) &handler, (void *) &i[0]);     pthread_create (&thread_b, null, (void *) &handler, (void *) &i[1]);      pthread_join(thread_a, null);     pthread_join(thread_b, null);      sem_destroy(&mutex); /* destroy semaphore */      /* exit */       exit(0); } /* main() */  void handler ( void *ptr ) {     int x;      x = *((int *) ptr);     printf("thread %d: waiting enter critical region...\n", x);     sem_wait(&mutex);       /* down semaphore */     /* start critical region */     printf("thread %d: in critical region...\n", x);     printf("thread %d: counter value: %d\n", x, counter);     printf("thread %d: incrementing counter...\n", x);     counter++;     printf("thread %d: new counter value: %d\n", x, counter);     printf("thread %d: exiting critical region...\n", x);     /* end critical region */         sem_post(&mutex);       /* semaphore */      pthread_exit(0); /* exit thread */ } 


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -