source: trunk/threads-peterson.c@ 2

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

Importazione sorgenti

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