source: trunk/threads-sem.c@ 26

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

Concorrenza 2013

File size: 1.5 KB
RevLine 
[2]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
[25]11void down(sem_t *s){
[2]12 if (sem_wait(s) < 0){
13 perror("Errore semaforo (down)");
14 exit(1);
15 }
16}
17
[25]18void up(sem_t *s){
[2]19 if (sem_post(s) < 0){
20 perror("Errore semaforo (up)");
21 exit(1);
22 }
23}
24
[25]25int shared = 0;
26pthread_t p1, p2;
27sem_t ss;
28
29void* run(void* s){
30 while (down(&ss),
31 shared < 10) {
[2]32 sleep(1);
[25]33 printf("Processo thread (%p). s = %d\n",
34 pthread_self(), shared);
35 if (!(shared < 10)){
[2]36 printf("Corsa critica!!!!\n");
37 abort();
38 }
[25]39 shared += 1;
40 up(&ss);
41 pthread_yield();
[2]42 }
[25]43 up(&ss);
44 return NULL;
[2]45}
46
47
[25]48
[2]49int main(void){
50
[25]51 if (sem_init(&ss,
[2]52 0 /* thread local semaphore */,
[25]53 1 /* init value */
[2]54 ) < 0){
55 perror("Errore semaforo");
56 exit(1);
57 }
58
[25]59 pthread_create(&p1, NULL, run, NULL);
60 pthread_create(&p2, NULL, run, NULL);
[2]61
[25]62 pthread_join(p1, NULL);
63 pthread_join(p2, NULL);
64
65 sem_destroy(&ss);
66
[2]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.