source: trunk/threads-peterson.c@ 19

Last change on this file since 19 was 15, checked in by Mattia Monga, 13 years ago

Aggiornati 2012

File size: 2.7 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
10
11void enter_section(int process, int* turn, int* interested)
12{
13 int other = 1 - process;
14 interested[process] = 1;
15 *turn = process;
16 while (*turn == process && interested[other]){
17 printf("Busy waiting di %d\n", process);
18 }
19}
20
21void leave_section(int process, int* interested)
22{
23 interested[process] = 0;
24}
25
26int run(const int p, void* s)
27{
[15]28 int* shared = (int*)s; // alias per comodit\`a
29 while (enter_section(p, &shared[1], &shared[2]), shared[0] < 10) {
[2]30 sleep(1);
31 printf("Processo figlio (%d). s = %d\n",
32 getpid(), shared[0]);
33 if (!(shared[0] < 10)){
34 printf("Corsa critica!!!!\n");
35 abort();
36 }
37 shared[0] += 1;
[15]38 leave_section(p, &shared[2]);
[2]39 }
[15]40 leave_section(p, &shared[2]);// il test nel while \`e dopo enter\_section
41
[2]42 return 0;
43}
44
45int run0(void*s){ return run(0, s); }
46int run1(void*s){ return run(1, s); }
47
48
49int main(void){
50
51 int shared[4] = {0 , 0, 0, 0};
52
53 /* int clone(int (*fn)(void *),
54 * void *child_stack,
55 * int flags,
56 * void *arg);
57 * crea una copia del chiamante (con le caratteristiche
58 * specificate da flags) e lo esegue partendo da fn */
59 if (clone(run0, /* il nuovo
60 * processo esegue run(shared), vedi quarto
61 * parametro */
62 malloc(4096)+4096, /* lo stack del nuovo processo
63 * (cresce verso il basso!) */
[15]64 CLONE_VM | SIGCHLD, /* la (virtual) memory \`e condivisa */
[2]65 shared) < 0){
66 perror("Errore nella creazione");
67 exit(1);
68 }
69
70 if (clone(run1, malloc(4096)+4096, CLONE_VM | SIGCHLD, shared) < 0){
71 perror("Errore nella creazione");
72 exit(1);
73 }
74
75 /* Memoria condivisa: i due figli nell'insieme eseguono 10 o
[15]76 * 11 volte con possibili corse critiche. Il padre
[2]77 * condivide shared[0] con i figli */
78
79 while(shared[0] < 10) {
80 sleep(1);
81 printf("Processo padre. s = %d %d %d %d\n",
82 shared[0],
83 shared[1],
84 shared[2],
85 shared[3]);
86 }
87 return 0;
88}
89
90
91
92
93
94
95
96/* Local Variables: */
97/* compile-command: "make -k " */
98/* End: */
Note: See TracBrowser for help on using the repository browser.