source: trunk/threads-sem.c

Last change on this file was 25, checked in by Mattia Monga, 11 years ago

Concorrenza 2013

File size: 1.5 KB
Line 
1/* Copyright (C) 2009 by Mattia Monga <mattia.monga@unimi.it> */
2/* $Id$ */
3
4#include <unistd.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <signal.h>
8#include <sched.h>
9#include <semaphore.h>
10
11void down(sem_t *s){
12 if (sem_wait(s) < 0){
13 perror("Errore semaforo (down)");
14 exit(1);
15 }
16}
17
18void up(sem_t *s){
19 if (sem_post(s) < 0){
20 perror("Errore semaforo (up)");
21 exit(1);
22 }
23}
24
25int shared = 0;
26pthread_t p1, p2;
27sem_t ss;
28
29void* run(void* s){
30 while (down(&ss),
31 shared < 10) {
32 sleep(1);
33 printf("Processo thread (%p). s = %d\n",
34 pthread_self(), shared);
35 if (!(shared < 10)){
36 printf("Corsa critica!!!!\n");
37 abort();
38 }
39 shared += 1;
40 up(&ss);
41 pthread_yield();
42 }
43 up(&ss);
44 return NULL;
45}
46
47
48
49int main(void){
50
51 if (sem_init(&ss,
52 0 /* thread local semaphore */,
53 1 /* init value */
54 ) < 0){
55 perror("Errore semaforo");
56 exit(1);
57 }
58
59 pthread_create(&p1, NULL, run, NULL);
60 pthread_create(&p2, NULL, run, NULL);
61
62 pthread_join(p1, NULL);
63 pthread_join(p2, NULL);
64
65 sem_destroy(&ss);
66
67 return 0;
68}
69
70
71
72
73
74
75
76/* Local Variables: */
77/* compile-command: "make -k " */
78/* End: */
Note: See TracBrowser for help on using the repository browser.