Concurrence complments Cnam Paris jeanmichel Douin douin au
- Slides: 59
Concurrence compléments Cnam Paris jean-michel Douin, douin au cnam point fr 19 Mars 2007 Notes de cours NSY 102 1
Bibliographie utilisée premier support + [SCHM 00] Schmidt, D. , Stal, M. , Rohnert, H. , Buschmann, F. , Patternoriented Software Architecture, John Wiley & Sons, 2000. NSY 102 2
Sommaire • java. lang. Thread – Exemples supplémentaires – wait/notify, notify. All compléments • java. lang. Thread. Group • Synchronisation, patrons – faible : Producteur/consommateur – forte : Rendez Vous • java. util. concurrent • Patrons selon M. Grand NSY 102 3
Exemple déjà vu public class T extends Thread { public void run(){ while(true){ System. out. println("dans " + this + ". run"); } } } public class Exemple { public static void main(String[] args) { T t 1 = new T(); T t 2 = new T(); T t 3 = new T(); t 1. start(); t 2. start(); t 3. start(); while(true){ System. out. println("dans Exemple. main"); } } } NSY 102 4
Un autre exemple [extrait de Java Threads p 17] import java. awt. *; class Timer. Thread extends Thread{ private Component comp; private int time. Diff; public Timer. Thread(Component comp, int time. Diff){ this. comp = comp; this. time. Diff = time. Diff; } public void run(){ while( !is. Interrupted()){ try{ comp. repaint(); // déclenchement cyclique sleep(time. Diff); }catch(Interrupted. Exception e) {} } NSY 102 5
Un autre exemple suite public class Animation extends java. applet. Applet{ private Image Diapositives[]; private Timer. Thread timer; public void init(){ Diapositives = new Image[100]; // int i = 0; String Nom; // chargement des Diapositives[i] = get. Image(get. Code. Base(), Nom + "jpg"); } public void start(){ timer = new Timer. Thread(this, 1000); //this est un Component timer. start(); } public void stop(){ timer. interrupt(); timer = null; } public void paint( Graphics g){ g. draw. Image(Diapositives[i], 0, 0, null); }} NSY 102 6
Applette + Requête HTTP cyclique public class Applette. DS 2438 extends Applet implements Action. Listener, Runnable { public void init(){ t = new Thread(this); t. start(); } public void stop(){t. interrupt(); } public void run() { while(!t. is. Interrupted()){ long top = System. current. Time. Millis(); try{ Thread. sleep(duree. De. Latence); Data. Input. Stream is = new Data. Input. Stream(new URL(url. Request). open. Stream()); String str = is. read. Line(); // traiter le retour ……… NSY 102 7
Accès aux ressources • Exclusion mutuelle – synchronized • Moniteur de Hoare – Variables condition NSY 102 8
Moniteur en Java, usage de synchronized Construction synchronized • synchronized(obj){ • // ici le code atomique sur l ’objet obj • } class C { synchronized void p(){ ……} } ////// ou ////// class C { void p(){ synchronized (this){……} }} NSY 102 9
Une ressource en exclusion mutuelle public class Ressource { private double valeur; synchronized double lire(){ return valeur; } synchronized void ecrire(double v){ valeur = v; } } Le langage garantit l ’atomicité en lecture et écriture des variables des types primitifs comme byte, char, short, int, float, reference (Object) mais ce n ’est pas le cas pour long et double NSY 102 10
Une file de messages import java. util. Vector; public class File. De. Messages { private Vector<Object> la. File = new Vector<Object>(); public synchronized void envoyer(Object obj) { la. File. add. Element(obj); } public synchronized Object recevoir () { if (la. File. size() == 0){ return null; }else{ Object obj = la. File. first. Element(); la. File. remove. Element. At(0); return obj; } }} NSY 102 11
Moniteur de Hoare • Un moniteur définit une forme de module partagé dans un environnement parallèle • Il encapsule des données et définit les procédures d ’accès à ces données • Le moniteur assure un accès en exclusion mutuelle aux données qu ’il encapsule • Synchronisation par les variables conditions : Abstraction évitant la gestion explicite de files d ’attente de processus bloqués • • L ’opération wait bloque l ’appelant L ’opération notify débloque éventuellement un processus bloqué à la suite d ’une opération wait sur le même moniteur voir : http: //www. enseeiht. fr/~padiou/2 AI/SYNCHRO/main. pdf NSY 102 12
Mécanisme de synchronisation • L ’évolution d ’un processus peut-être momentanément bloqué tant qu ’une condition n ’est pas vérifiée • Lorsque la condition attendue devient vraie, un ou plusieurs processus peuvent continuer • Mécanisme de synchronisation en Java lié au moniteur – la classe java. lang. Object – wait() et notify() • NSY 102 Extrait de voir http: //www. enseeiht. fr/~padiou/2 AI/SYNCHRO/main. pdf 13
Le joueur de ping-pong // Entrelacement de ping et de pong public class Table. En. Simplements Table{ private int coup = PING; public synchronized void jouer. Ping(){ if (coup == PING) try{ wait(); }catch(Interrupted. Exception e){}; coup = PING; notify(); } interface Table { final static int PING=0; final static int PONG=1; void jouer. Ping(); void jouer. Pong(); } public synchronized void jouer. Pong(){ if (coup == PONG) try{ wait(); }catch(Interrupted. Exception e){}; coup = PONG; notify(); } } NSY 102 14
Le joueur de ping-pong (2) public class Joueur extends Thread{ private static Table. En. Simple table; private static Joueur joe; public static void main(String args[]){ while (true){ table. jouer. Ping(); // le main est un joueur ping }} public void run(){ while (true){ table. jouer. Pong(); }} static{ table = new Table. En. Simple(); joe = new Joueur(); joe. start(); }} NSY 102 15
Exemples suite • En OU – L’un des Threads se termine • En ET – Tous les Threads doivent se terminer – Extraits de Doug Lea • http: //g. oswego. edu/dl/ NSY 102 16
Le plus rapide ou attente en OU public class Recherche. En. OU{ // Squelette de programme protected Thread t 1, t 2; protected String resultat; public synchronized String recher(){ while(t 1!=null && t 2 != null) // attendre la fin de la précédente recherche try{ wait(); }catch(Interrupted. Exception ie){} t 1 = new Thread(this); // en paramètre cette instance, voir méthode succes t 2 = new Thread(this); t 1. start(); t 2. start(); while(resultat == null) // le résultat est arrivé try{ wait(); }catch(Interrupted. Exception ie){} // synchro ici t 1 = t 2 = null; notify. All(); return resultat; } public synchronized void succes(String res){ resultat = res; if(t 1 != null) t 1. interrupt(); if(t 2 != null) t 2. interrupt(); notify. All(); }} NSY 102 // appelée par t 1 ou t 2 17
Shéma de l’attente en Ou • Discussion : – Ici la méthode appelée par le client (succes dans l’exemple, ou « callback » ) est utilisée pour « débloquer » et autoriser la poursuite de l’exécution de la méthode recher – Principe apparenté au Patron Half-Synch/half-Asynch (abordé par la suite) • Découplage appels synchrones/asynchrones, ici par l’appel de notify. All NSY 102 18
Attente en « ET » public class En. ET{ protected Thread t 1; protected Thread t 2; protected String res 1, res 2; public synchronized String cumuler(){ t 1 = new Thread(); // en paramètre cette instance t 2 = new Thread(); t 1. start(); t 2. start(); try{ t 1. join(); t 2. join(); }catch(Interrupted. Exception ie){ t 1. interrupt(); t 2. interrupt(); return null; } return res 1 + res 2; } // appelées par t 1 et t 2 public synchronized void succes. T 1(String r 1){ res 1 = r 1; } public synchronized void succes. T 2(String r 2){ res 2 = r 2; } } NSY 102 19
Patron Producteur/Consommateur • Une Ressource partagée – Un producteur et un consommateur • NSY 102 Diagrammes produits avec start. UML, http: //staruml. sourceforge. net/en/ 20
Moniteur et variable condition public class Ressource { private int val = 0; private boolean val_Presente = false; public synchronized int lire(){ while (!val_Presente){ try{ wait(); }catch(Exception e){} } val_Presente = false; notify(); return val; } public synchronized void ecrire(int x){ while (val_Presente){ try{ wait(); }catch(Exception e){} } val = x; val_Presente = true; notify(); }} NSY 102 21
Moniteur et variable condition public class Ressource{ private int val = 0; private boolean val_Presente = false; public synchronized int lire(){ while (!val_Presente){ try{ wait(); }catch(Exception e){} } val_Presente = false; notify. All(); return val; } public synchronized void ecrire(int x){ while (val_Presente){ try{ wait(); }catch(Exception e){} } val = x; val_Presente = true; notify. All(); }} NSY 102 22
notify et notify. All • Discussion, Commentaires. . . NSY 102 23
Schéma d ’une condition gardée synchronized (this){ while (!condition){ try{ wait(); }catch (Exception e){} } } synchronized (this){ condition = true; notify(); // ou notify. All() } notes : synchronized(this) engendre la création d ’un moniteur associé à this wait(), ou notify() (pour this. wait() ou this. notify()) this. wait() : mise en attente sur le moniteur associé à this, this. notify() réveille l’un des processus en attente sur ce moniteur (lequel ? ) NSY 102 24
Divers • Divers et obsolète – Sémaphore binaire – Sémaphore à compte • Interblocages toujours possibles NSY 102 25
Divers : Un Sémaphore binaire • Java a implicitement les sémaphores de ce type Object mutex = new Object(); synchronized(mutex){ …. …. } NSY 102 // P(mutex) // V(mutex) 26
Divers : Un Sémaphore à compte [Lea p 97] public final class Counting. Semaphore{ private int count; Counting. Semaphore(int initial. Count){ this. count = initial. Count; } public synchronized void P(){ while( this. count <= 0){ // if(this. count <= 0) try{ wait(); }catch(Interrupted. Exception e){} } this. count--; } public synchronized void V(){ this. count++; notify(); }} NSY 102 27
Interblocage. . class Un. Exemple{ protected Object variable. Condition; public synchronized void aa(){ … synchronized(variable. Condition){ while (!condition){ try{ variable. Condition. wait(); // attente sur variable. Condition // dans une instance de Un. Exemple }catch(Interrupted. Exception e){} }} public synchronized void bb(){ // aucun processus ne peut accèder a bb() // donc aucune notification possible sur variable. Condition synchronized(variable. Condition){ variable. Condition. notify. All(); }} NSY 102 28
Etats d'un "Thread" bloqué notify() notifyall() moniteur Inconnu sleep() wait() moniteur stop() Arrêté (pour toujours) yield() start() stop() fin de run() Eligible Actif Attribution du processeur par l'ordonnanceur NSY 102 29
Moniteur et variable condition: Un. Buffer. java class Un. Buffer extends java. util. Vector{ public Un. Buffer ( int taille ){super(taille); } public synchronized void deposer (Object item){ while (element. Count==capacity()){ try{ wait(); }catch(Exception e){} } notify. All(); add. Element(item); } NSY 102 public synchronized Object retirer (){ while (is. Empty()){ try{ wait(); }catch(Exception e){} } notify. All(); Object first. Element = first. Element(); remove. Element. At(0); return first. Element; }} 30
Passage de message en Rendez-vous Communication en synchronisation forte, uni-directionnelle, point à point, sans file d’attente( modèle CSP) C. ecrire(i) C. lire() NSY 102 Test. Rendez. Vous. java C 1. ecrire() Un. Canal. java Emetteur. java C 1. lire(i) R Recepteur. java E 31
Rendez-vous : Un. Canal. java public class Un. Canal { private int val = 0; private boolean emetteur_Present=false, recepteur_Present=false; public synchronized int lire(){ recepteur_Present = true; if (!emetteur_Present){ try{ wait(); }catch(Exception e){} } recepteur_Present = false; notify(); return val; } public synchronized void ecrire(int x){ val = x; // le canal en Rd. V est toujours vide emetteur_Present = true; notify(); if (!recepteur_Present){ try{ wait(); }catch(Exception e){} } emetteur_Present = false; // il a redemmarre }} NSY 102 32
Rendez-vous : Une utilisation public class Test. Thread. Rendez. Vous{ public static void main(String args[]){ Un. Canal C = new Un. Canal(); Emetteur E = new Emetteur(C); Recepteur R = new Recepteur(C); E. start("Emetteur E", 5); R. start("Recepteur R", 5); try{ Thread. sleep(2000); E. stop(); R. stop(); }catch(Exception e){} }} NSY 102 33
Un réseau de Thread en pipeline Chaque Thread issu de chaque instance de la classe Element réalise la fonction f, soit sortie=f(entree), Chaque Lien est un canal en Rendez-vous Element e pipe[0] s=f(e) s Element s=f(e) pipe[1] pipe[size-1] Un. Canal pipe[] = new Un. Canal[size]; NSY 102 34
La classe Element interface Operation{ public int f(int x); } class Element implements Runnable{ private Un. Canal entree, sortie; private Thread local; private Operation opr; Element(Un. Canal entree, Un. Canal sortie, Operation opr){ this. entree = entree; this. sortie = sortie; this. opr = opr; local = new Thread(this); local. start(); } public void run(){ while(true){ int x= entree. lire(); int y = opr. f(x); sortie. ecrire(y); un Element entree sortie y=opr. f(x) }}} NSY 102 35
La classe Pipeline class Pipeline{ private Un. Canal pipe[]; private int size; public Pipeline(int size, Operation opr){ pipe = new Un. Canal[size]; for(int i=0; i<size; i++){ pipe[i] = new Un. Canal(); } for(int i=0; i<size-1; i++){ new Element(pipe[i], pipe[i+1], opr); } this. size = size; } public void envoyer(int val){ pipe[0]. ecrire(val); } public int recevoir(){ return pipe[size-1]. lire(); }} NSY 102 36
La classe Test. Pipeline : 2 réseaux public class Test. Pipeline{ public static void main(String args[]){ Pipeline pipe = new Pipeline(30, new Inc()); pipe. envoyer(5); +1 +1 -1 -1 int val = pipe. recevoir(); System. out. println("pipe 1, valeur recue : " + val); Pipeline pipe 2 = new Pipeline(30, new Dec()); pipe 2. envoyer(val); val = pipe 2. recevoir(); System. out. println("pipe 2, valeur recue : " + val); }} class Inc implements Operation{ public int f (int x){ return x+1; }} NSY 102 class Dec implements Operation{ public int f (int x){ return x-1; }} 37
Héritage • B dérive de A – – – B a accès aux membres protégés et publics de A B implémente toutes les interfaces de A B exporte tous les membres publics de A B ne peut restreindre les accès aux membres de A B peut rendre publique une méthode protégée de A toute méthode de B ayant la même signature qu ’une méthode de A protégée ou publique redéfinit celle-ci – B peut ajouter de nouveaux membres, données ou méthodes NSY 102 38
Héritage et Thread … Héritage de méthodes engendrant des Threads public class Auto. Thread implements Runnable{ private Thread local; public Auto. Thread(){ local = new Thread( this); local. start(); } public void run(){ if( local == Thread. current. Thread()){ while(true){ System. out. println("dans Auto. Thread. run"); } }} Le nombre d ’instances et le nombre de Thread diffèrent selon l ’usage et la redéfinition de la méthode run() NSY 102 39
Héritage et Thread • class Auto. Thread. Extends extends Auto. Thread { • private Thread local; • public Auto. Thread. Extends (){ • super(); • local = new Thread( this); • local. start(); • } si auto = new Auto. Thread. Extends(); et pas de redéfinition de run dans la classe dérivée alors « 1 Thread / 1 run » et redéfinition de run dans la classe dérivée alors 1 Thread / 1 run et redéfinition de run dans la classe dérivée et appel de super. run() alors 2 Threads …. Utilisation recommandée de l ’identification du Thread par : • public void run(){ • if( local == Thread. current. Thread()){. . . NSY 102 40
Héritage et synchronisation • synchronized est propre à la classe • Une méthode qualifiée peut être redéfinie dans une sous-classe en enlevant cette construction • La sous-classe doit assurer elle-même la bonne redéfinition des méthodes de sa super-classe NSY 102 41
Ordonnancement suite • A priorité, – – – • • • NSY 102 void set. Priority() int get. Priority() Thread. MIN_PRIORITY Thread. MAX_PRIORITY Thread. NORM_PRIORITY (1) (10) (5) void suspend() et void resume() … void join() static void yield(); void set. Daemon(boolean on); boolean is. Daemon(); 42
Etats d'un "Thread" bloqué stop() notifyall() resume() Inconnu sleep() wait() suspend() stop() start() Arrêté (pour toujours) stop() yield() set. Priority() Elligible Actif Attribution du processeur par l'ordonnanceur NSY 102 43
Ordonnancement • A priorité égale : la spécification n'impose rien – Pas de soucis d'équité – A chaque ré-ordonnancement (si il existe) le processeur est attribué à un autre processus de priorité égale – Après un wait() c'est l'un des processus qui est choisi • Sous Windows 95(JDK 1. 1. 4), et Mac. OS (JDK 1. 0. 2) – Un tourniquet est déjà installé • Sous Solaris / linux – À vérifier NSY 102 44
Ordonnanceur de type tourniquet class Simple. Scheduler extends Thread{ // Java Threads page 139 private int timeslice; Simple. Scheduler(int t){ timeslice = t; set. Priority( Thread. MAX_PRIORITY); set. Daemon(true); } public void run (){ while(true){ try{ sleep(timeslice); }catch(Exception e){} } NSY 102 45
Exemple d'utilisation class Balle extends Thread{ private String Id; Balle( String Id){ this. Id = Id; } public void run(){ while(true){ System. out. println(Id); } } } public class Test. Simple. Scheduler{ public static void main(String args[]){ new Simple. Scheduler(100). start(); Balle ping = new Balle("ping"); Balle pong = new Balle("pong"); ping. start(); pong. start(); } } NSY 102 46
Ordonnanceurs • Autres stratégies d ’ordonnancement • Ordonnanceurs à échéance – http: //www-cad. eecs. berkeley. edu/~jimy/java/ – http: //gee. cs. oswego. edu/dl/cpj/ NSY 102 47
java. lang. Thread. Group • Java. lang. Thread. Group (p. 477, Java in a Nutshell, 2 nd) • Rassembler plusieurs Thread – Changer l ’état de tous les Threads d ’un groupe • suspend, resume, stop, set. Max. Priority – Interroger l ’état des Threads… • is. Daemon, is. Destroyed, parent. Of. . . • Hiérarchiser les groupes de Threads • Theadr. Group(Thread. Group parent, . . . ), get. Parent NSY 102 48
Thread. Group, un exemple revisité : le Pipeline class Element implements Runnable{ …. Element(Thread. Group group, Un. Canal entree, Un. Canal sortie, Operation opr){. . . local = new Thread(group, this); … }} class Pipeline{. . . private Thread. Group group; public Pipeline(int size, Operation opr){ group = new Thread. Group(this. to. String()); for(int i=0; i<size-1; i++){ new Element(group, pipe[i], pipe[i+1], opr); } …. public void detruire(){ group. stop(); }} NSY 102 49
java. util. concurrent et les moniteurs un moniteur en 1. 5, voir java. util. concurrent. locks Exclusion mutuelle assurée par lock() et unlock()) Les variables condition Condition await() si une condition n’est pas satisfaite / wait - signal() ou signal. All() pour réveiller une thread bloquée lorsque la condition devient vraie. Les nouvelles méthodes sont définies dans le paquetage java. util. concurrent. locks NSY 102 50
Exmple extrait du jdk, Bounded. Buffer put class Bounded. Buffer { final Lock lock = new Reentrant. Lock(); final Condition not. Full = lock. new. Condition(); final Condition not. Empty = lock. new. Condition(); final Object[] items = new Object[100]; int putptr, takeptr, count; public void put(Object x) throws Interrupted. Exception{ lock(); try { while (count == items. length) not. Full. await(); items[putptr] = x; if (++putptr == items. length) putptr = 0; ++count; not. Empty. signal(); } finally { lock. unlock(); }} NSY 102 51
Bounded. Buffer, take public Object take() throws Interrupted. Exception { lock(); try { while (count == 0) not. Empty. await(); Object x = items[takeptr]; if (++takeptr == items. length) takeptr = 0; --count; not. Full. signal(); return x; } finally { lock. unlock(); } } } NSY 102 52
Design Pattern • Doug Lea – http: //gee. cs. oswego. edu/dl/cpj/index. html • Mark Grand – http: //www. mindspring. com/~mgrand/pattern_synopses. htm NSY 102 53
Single Threaded Execution design pattern NSY 102 54
Guarded Suspension NSY 102 55
Balking NSY 102 56
Read/Write Lock NSY 102 57
Two phase termination NSY 102 58
Annexe : Monitor de Hoare • L’original • http: //www. cse. ucsd. edu/classes/wi 07/cse 221/papers/hoare 74. pdf NSY 102 59
- Complments
- Douin apk
- Cnam apeiron
- Cnam la rochelle
- Cnam ceet
- Cnam conference
- Circumcenters
- "gilette"
- Concurrence directe et indirecte
- Force faiblesse nike
- Mala prohibita
- Concurrence pure et parfaite
- Marketing mix red bull
- Monopole oligopole
- Romeo and juliet summary act 1 scene 2
- Spermoculture paris 11
- La petite france paris
- 2 rue lord byron 75008 paris
- What is enp
- Outline map of france bordeaux nantes paris marseilles
- On paris ernest hemingway analysis a level
- Viktorija pariz
- Birkemåleren evolution
- Université paris 1
- Hudi
- Paris vs vikings
- Marine couverchel
- Ufr segmi nanterre
- Rizal second sojourn in paris and the universal exposition
- Visual cliff paradigm
- Injustus
- Cva paris nanterre edt
- Séjour scolaire paris
- Ca ile de france
- Both new hampshire and new york desire more territory
- Why rizal left london for paris in march 1899?
- Paris by night
- School trip to paris
- Paris traceroute
- Describe the scenario that led prince paris to kidnap helen
- Max beckmann party in paris
- Les plus belles vues de paris
- Piscine mythique paris
- Activity 5 work in pairs answer the questions
- Boston massacre timeline
- Viaje paris fin de curso
- Infn paris 12
- Dave paris romeo and juliet
- Loulou restaurant paris
- Ainhoa calvo
- Paris and friar lawrence
- Quien es paris
- Aeroclub paris aero
- Haikara restaurant paris
- [email protected]
- Paris school of economics ape
- Paris, a rainy day
- Université nanterre organigramme
- Romeo and juliet character quotes
- Maryse est ____ à paris