source: trunk/threads-isolated.c@ 15

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

Aggiornati 2012

File size: 1.9 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
10int run(void* s)
11{
12 int* shared = (int*)s; // alias per comodit\`a
13 while (shared[0] < 10) {
14 sleep(1);
15 printf("Processo figlio (%d). s = %d\n",
16 getpid(), shared[0]);
17 if (!(shared[0] < 10)){
18 printf("Corsa critica!!!!\n");
19 abort();
20 }
21 shared[0] += 1;
22 }
23 return 0;
24}
25
26
27int main(void){
28
29 int shared[2] = {0 , 0};
30 /* int clone(int (*fn)(void *),
31 * void *child_stack,
32 * int flags,
33 * void *arg);
34 * crea una copia del chiamante (con le caratteristiche
35 * specificate da flags) e lo esegue partendo da fn */
36 if (clone(run, /* il nuovo
37 * processo esegue run(shared), vedi quarto
38 * parametro */
39 malloc(4096)+4096, /* lo stack del nuovo processo
40 * (cresce verso il basso!) */
41 SIGCHLD, // in questo caso la clone \`e analoga alla fork
42 shared) < 0){
43 perror("Errore nella creazione");exit(1);
44 }
45 if (clone(run, malloc(4096)+4096, SIGCHLD, shared) < 0){
46 perror("Errore nella creazione");exit(1);
47 }
48
49 /* Isolati: ciascuno dei figli esegue 10 volte. */
50 // Per il padre shared[0] \`e \textbf{sempre} 0 */
51
52 while(shared[0] == 0) {
53 sleep(1);
54 printf("Processo padre. s = %d\n", shared[0]);
55 }
56 return 0;
57}
58
59
60
61
62
63
64
65/* Local Variables: */
66/* compile-command: "make -k " */
67/* End: */
Note: See TracBrowser for help on using the repository browser.