source: trunk/threads-tsl.c@ 2

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

Importazione sorgenti

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