Changes between Version 10 and Version 11 of AS6-TME-B7


Ignore:
Timestamp:
Apr 11, 2022, 8:28:07 PM (2 years ago)
Author:
franck
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • AS6-TME-B7

    v10 v11  
    171171Une barrière de synchronisation est utilisée pour synchroniser les étapes de calculs réalisés par plusieurs threads. Supposons que l'on souhaite exécuter deux threads en parallèle et que l'on veuille attendre que les deux aient terminé leur travail avant de recommencer un travail. Il faut que les deux threads se donnent rendez-vous à la fin de leur calcul.
    172172
     173{{{#!c
     174/*------------------------------------------------------------------------*\
     175   _     ___    __
     176  | |__ /'v'\  / /      \date        2022-04-11
     177  | / /(     )/ _ \     \copyright   2021-2022 Sorbonne University
     178  |_\_\ x___x \___/                  https://opensource.org/licenses/MIT
     179
     180\*------------------------------------------------------------------------*/
     181
     182#include <libc.h>
     183#include <thread.h>
     184
     185#define DELAY(n) for(int i=n;i--;) __asm__("nop");
     186
     187struct arg_s {                 // structure pour passer des args aux threads
     188    int delay;                 // délai qui simule une durée de calcul
     189    char *message;             // chaine de caractères
     190};
     191
     192thread_t t0, t1;               // 2 threads
     193struct arg_s a0, a1;           // les arguments des threads     
     194thread_barrier_t barrier;      // 1 barrière
     195
     196void * t0_fun (void * arg)     // thread qui sera instantié deux fois
     197{
     198    struct arg_s * a = arg;
     199    while (1) {                           // faire toujours
     200        fprintf (1, "%s\n", a->message);  //   afficher un message
     201        DELAY (a->delay);                 //   calcul (il faudrait un random)
     202        thread_barrier_wait (&barrier);   //   attendre l'autre instance
     203    };
     204}
     205
     206int main (void)
     207{
     208    thread_barrier_init (&barrier, 2);    // Créer une barrière pour 2
     209
     210    a0.delay = 500000;                    // args premier thread
     211    a0.message = "bonjour";
     212
     213    a1.delay = 2000000;                   // args deuxième thread
     214    a1.message = "salut";
     215
     216    thread_create (&t0, t0_fun, &a0);     // démarrer premier thread
     217    thread_create (&t0, t0_fun, &a1);     // démarrer deuxieme thread
     218
     219    for (int i = 0;i<3; i++) {            // main() bosse de son coté
     220        fprintf (0, "[%d] app is alive (%d)\n", clock(), i);
     221        DELAY(100000);
     222    }
     223
     224    void * trash;     
     225    thread_join (t1, &trash);
     226    thread_join (t0, &trash);
     227    return 0;
     228}
     229}}}
     230