Sezioni Critiche in C

From Sistemi Operativi
Revision as of 15:37, 12 October 2017 by Renzo (talk | contribs)
Jump to navigation Jump to search

Tutti questi esempi hanno NPROC thread che svolgono un loop MAX volte sommando 1 ad ogni iterazione ad una variabile globale condivisa val.

Se tutto va bene il risultato finale deve essere NPROC*MAX.

Dekker

#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include<sched.h>
#include<pthread.h>
#include<unistd.h>

#define MAX 400
#define STEP 10
#define NPROC 2

volatile long val = 0;
int need[NPROC];
int turn;

void *codet(void *arg) {
  uintptr_t id = (uintptr_t) arg;
  int count;
  long tmp;
  for (count=0; count  < MAX; count++) {
    /* enter */
    need[id] = 1;
    while (need[1 - id]) {
      if (turn != id) {
        need[id] = 0;
        while (turn != id)
          sched_yield();
        need[id] = 1;
      }
    }
    /* /enter */
    tmp = val;
    //usleep(rand() % 2);
    val = tmp + 1;
    if (count % STEP == 0)
      printf("%d %ld\n",id,val);
    /* exit */
    turn = 1 - id;
    need[id] = 0;
    /* /exit */
  }
}

int main(int argc, char *argv[]) {
  uintptr_t i;
  pthread_t t[NPROC];
  srand(time(NULL));
  for (i=0; i<NPROC; i++)
    pthread_create(&t[i], NULL, codet, (void *) i);
  for (i=0; i<NPROC; i++)
    pthread_join(t[i], NULL);
  printf("%d %d\n",val,NPROC*MAX);
}