source: trunk/threads-shared.c@ 26

Last change on this file since 26 was 26, checked in by Mattia Monga, 10 years ago

Programmi 2014

File size: 1.9 KB
RevLine 
[2]1/* Copyright (C) 2009 by Mattia Monga <mattia.monga@unimi.it> */
2/* $Id$ */
[26]3#define _GNU_SOURCE
[2]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{
[15]12 int* shared = (int*)s; // alias per comodit\`a
[2]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!) */
[15]41 CLONE_VM | SIGCHLD, // (virtual) memory condivisa
[2]42 shared) < 0){
[15]43 perror("Errore nella creazione");exit(1);
[2]44 }
45
46 if (clone(run, malloc(4096)+4096, CLONE_VM | SIGCHLD, shared) < 0){
[15]47 perror("Errore nella creazione");exit(1);
[2]48 }
49
50 /* Memoria condivisa: i due figli nell'insieme eseguono 10 o
[15]51 * 11 volte: \`e possibile una corsa critica. Il padre
[2]52 * condivide shared[0] con i figli */
53
[15]54 while(shared[0] < 10) {
[2]55 sleep(1);
56 printf("Processo padre. s = %d\n", shared[0]);
57 }
58 return 0;
59}
60
61
62
63
64
65
66
67/* Local Variables: */
68/* compile-command: "make -k " */
69/* End: */
Note: See TracBrowser for help on using the repository browser.