source: trunk/threads-tsl.c@ 26

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

Programmi 2014

File size: 2.6 KB
Line 
1/* Copyright (C) 2009 by Mattia Monga <mattia.monga@unimi.it> */
2/* $Id$ */
3#define _GNU_SOURCE
4
5#include <unistd.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <signal.h>
9#include <sched.h>
10
11
12void enter_section(int *s); /* in enter.asm */
13void leave_section(int *s){ *s = 0; }
14
15int run(const int p, void* s){
16 int* shared = (int*)s; // alias per comodit\`a
17 while (enter_section(&shared[1]), shared[0] < 10) {
18 sleep(1);
19 printf("Processo figlio (%d). s = %d\n",
20 getpid(), shared[0]);
21 fflush(stdout);
22 if (!(shared[0] < 10)){
23 printf("Corsa critica!!!!\n");
24 abort();
25 }
26 shared[0] += 1;
27 leave_section(&shared[1]);
28 sched_yield();
29 usleep(50);
30 }
31 leave_section(&shared[1]); // il test nel while \`e dopo enter\_section
32 return 0;
33}
34
35int run0(void*s){ return run(0, s); }
36int run1(void*s){ return run(1, s); }
37
38
39int main(void){
40
41 int shared[4] = {0 , 0, 0, 0};
42
43 /* int clone(int (*fn)(void *),
44 * void *child_stack,
45 * int flags,
46 * void *arg);
47 * crea una copia del chiamante (con le caratteristiche
48 * specificate da flags) e lo esegue partendo da fn */
49 if (clone(run0, /* il nuovo
50 * processo esegue run(shared), vedi quarto
51 * parametro */
52 malloc(4096)+4096, /* lo stack del nuovo processo
53 * (cresce verso il basso!) */
54 CLONE_VM | SIGCHLD, /* la (virtual) memory \`e condivisa */
55 shared) < 0){
56 perror("Errore nella creazione");
57 exit(1);
58 }
59
60 if (clone(run1, malloc(4096)+4096, CLONE_VM | SIGCHLD, shared) < 0){
61 perror("Errore nella creazione");
62 exit(1);
63 }
64
65 /* Memoria condivisa: i due figli nell'insieme eseguono 10 o
66 * 11 volte: \`e possibile una corsa critica. Il padre
67 * condivide shared[0] con i figli */
68
69 while(shared[0] < 10) {
70 sleep(1);
71 printf("Processo padre. s = %d %d %d %d\n",
72 shared[0],
73 shared[1],
74 shared[2],
75 shared[3]);
76 fflush(stdout);
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.