source: trunk/threads-tsl.c@ 25

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

Aggiornati 2012

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