Computer Networks. Process Cooperation Multithreaded Programming in Java. Laszlo Böszörmenyi Computer Networks Processes - 1

Size: px
Start display at page:

Download "Computer Networks. Process Cooperation Multithreaded Programming in Java. Laszlo Böszörmenyi Computer Networks Processes - 1"

Transcription

1 Computer Networks Process Cooperation Multithreaded Programming in Java ß ß Laszlo Böszörmenyi Computer Networks Processes - 1

2 Processes and threads A process is a sequential flow of control that is able to cooperate with other processes Heavy-weight light-weight process Thread (of control) lightweight process We use them as synonyms, if difference irrelevant Address space Context Context switch (Heavy) Process Own Large (file descriptors, I/O buffers) Slow Thread Common (but: own stack) Small (a few registers) Fast Laszlo Böszörmenyi Computer Networks Processes - 2

3 Parallel and concurrent execution True parallel execution Processes run on own processor, with own register set Concurrent (quasi parallel) execution One processor and register set is shared Registers have to be saved and restored Usually slow, but still meaningful for parallel problems Processor Execution Parallel Own Truly parallel Quasi parallel Common Virtually parallel (concurrent) Laszlo Böszörmenyi Computer Networks Processes - 3

4 Creating processes (fork & join) Calling a procedure suspends the caller Forking a thread creates two parallel threads Each with an own stack Let be P1 and P2 procedures P1 call P1 fork waits. P2 runs runs P2 runs.. return join Laszlo Böszörmenyi Computer Networks Processes - 4

5 Creating threads in Java A thread is created by creating an instance of either A subclass of the class Thread or A class that implements the Runnable interface Some basic methods of threading The run method must be overridden by required code Call of start causes the run method to be forked join suspends the caller until the target thread completes and merges the 2 threads into 1 sleep causes thread to sleep for a given time (msecs) yield lets run other threads sleep(0) stop, suspend : DO NOT USE (deprecated anyway) Laszlo Böszörmenyi Computer Networks Processes - 5

6 Example, thread as a subclass class MyThread extends Thread { // MyThread is subclass of Thread public void run() { // overrides Threads run System.out.println("Hello, this is " + getname()); } // run } // MyThread public class ExtendedThread { static public void main(string args[]) { MyThread a = new MyThread(); MyThread b = new MyThread(); a.start(); // forks run of a } } // main Arbitrary order Hello, this is Thread-0 This is main Hello, this is Thread-1 main T0 T1 b.start(); // forks run of b /*3 Threads: a, b, and main run now quasi-parallel*/ System.out.println("This is " + Thread.currentThread().getName()); Laszlo Böszörmenyi Computer Networks Processes - 6

7 Example, thread implementing runnable class MyThread implements Runnable { public void run() { System.out.println("Hello, this is " + Thread.currentThread().getName()); /* Unqualified getname is now unknown! */ } // run } // MyThread public class RunnableThread { static public void main(string s[]) { MyThread work2do; Thread a, b; work2do = new MyThread(); a = new Thread(work2do); b = new Thread(work2do); a.start(); b.start(); main T0 T1 System.out.println("This is " + Thread.currentThread().getName()); } } Arbitrary order Hello, this is Thread-0 This is main Hello, this is Thread-1 Laszlo Böszörmenyi Computer Networks Processes - 7

8 Process cooperation Synchronization Processes meet in a point of time ( rendez-vous ) Mutual exclusion and conditional synchronization Communication Synchronous Processes exchange data at synchronization point Asynchronous Exchange data via persistent medium (files, mailboxes, buffers) Kinds of data exchange Common memory, if available in threads Messages, via communications channels If common memory not available normal for distributed systems Laszlo Böszörmenyi Computer Networks Processes - 8

9 Critical sections A critical section (CS) is a piece of code, in which More than one process access shared data At least on of them wants to modify these data Criteria for correct handling Mutual exclusion (mutex) at most 1 process inside Progress deadlock is avoided Limited wait starvation is avoided Rules of a correct protocol Inside the CS at most 1 process CS must be left in finite time otherwise no progress. In case of crash enforce exit If a process terminates in the rest, this must not have influence on the other processes Steps of mutex Entry protocol Critical section Exit protocol Rest Laszlo Böszörmenyi Computer Networks Processes - 9

10 Mutual exclusion in Java synchronized keyword marks as critical section an entire method synchronized void P () { // enter // All statements of P are executed under mutual exclusion } // exit a piece of code inside a method void P () { //... Non-synchronized code synchronized (this) { // enter // These statements are executed under mutual exclusion } // exit //... Non-synchronized code } // P Laszlo Böszörmenyi Computer Networks Processes - 10

11 Conditional synchronization Entering a CS via mutex is unconditional An action may need a precondition fulfilled later Conditional waiting is necessary CS must be left! When condition fulfilled: notify waiting threads Semaphores can be used for both (see later) Mutual exclusion with binary semaphores Conditional synchronization with general semaphores Examples (see later) Bounded buffer Dining philosophers Readers / writers problem Laszlo Böszörmenyi Computer Networks Processes - 11

12 Monitors (C. A. R. Hoare) Combines the idea of hiding and concurrency A monitor is a special container (class or module) Mutual exclusion is per definition guaranteed for all procedures of a monitor Condition variables with special operations Wait The waiting thread relinquishes the CS (releases lock) Signal (notify) Awakes a thread, which re-enters the CS (gets lock) Awakening my be Immediate (preemptive) or delayed (non-preemptive) Explicit or implicit (automatically by changing the condition) Laszlo Böszörmenyi Computer Networks Processes - 12

13 Conditional synchronization in Java (1) Each object provides the methods wait, notify, notifyall Wait suspends the thread releases the lock on the object it waits for all other locks are retained Awaking waiting threads by notify and notifyall notification reacquires the lock (reenters the CS) notify wakes one waiting thread notifyall wakes all threads waiting on the object notification remains without effect, if no waiting thread This may cause errors: If signal comes earlier then wait Laszlo Böszörmenyi Computer Networks Processes - 13

14 Conditional synchronization in Java (2) Signaling is explicit and delayed Additional state-check is necessary, because another thread might have changed the condition in between Proper pattern while (!condition) try {wait();} catch ( ) {}; Thread leaves CS until awaken Re-check condidtion Never use if (!condition) try {wait();} catch ( ) {}; A java class, where all methods are synchronized: a monitor Not perfectly the original Hoare-monitor The synchronized modifier must be set manually Awaking is delayed enabling notifyall (broadcast) CS regained Laszlo Böszörmenyi Computer Networks Processes - 14

15 Bounded buffer Definition Buffer has a finite capacity (length) Pointer in resp. out point to the next empty resp. filled slot in the buffer Counter used shows the actually filled slots The buffer builds a ring in and out are incremented modulo length Producer threads can deposit objects via put Producers has to wait if buffer full (used == length) Consumer threads can take objects via get Consumers has to wait if buffer empty (used == 0) Access to the buffer elements must be in a CS The CS must be temporarily relinquished if condition false Laszlo Böszörmenyi Computer Networks Processes - 15

16 cons i cons i cons i prod i prod i prod j Bounded buffer Implementation via monitor public class BoundedBufferMon { private int in, out, used = 0; private Object [] data; public BoundedBufferMon (int bufsize) { in = 0; out = 0; used = 0; data = new Object[bufSize]; // bufsize > 0! } // BoundedBufferSem public synchronized Object get () { while (used == 0) try {wait();} catch(interruptedexception e) {}; // hidden (private) variables Object d = data[out]; used > 0! CS regained out = (out + 1) % data.length; if (used-- == data.length) notifyall(); Advance return d; ring pointer Awake waiting } // get producers public synchronized void put (Object d) { while (used == data.length) try {wait();} catch(interruptedexception e) {}; data[in] = d; in = (in + 1) % data.length; if (used++ == 0) notifyall(); } // put } // BoundedBufferMon Thread leaves CS until awaken used < length! CS regained Laszlo Böszörmenyi Computer Networks Processes - 16

17 Bounded buffer Producer thread class Producer extends Thread { // Subclass of Thread private int myid; // Thread identifier private BoundedBufferMon buf; // Buffer shared with other threads private boolean isrunning = true; Producer(int identifier, BoundedBufferMon buffer) { // Constructor myid = identifier; buf = buffer; } public void stopp() { isrunning = false; } public void run() { // overrides run method of the Thread class while (isrunning) { String message = new String("P-" + myid + ": " + Calendar.getInstance().getTimeInMillis() % 10000); buf.put(message); try {Thread.sleep(myId* );} catch(interruptedexception e) {} } // while buf.put("stop"); } // run } // Producer Laszlo Böszörmenyi Computer Networks Processes - 17

18 Bounded buffer Consumer thread class Consumer extends Thread { // Subclass of Thread private int myid; // Thread identifier private int RunningP = BufUserMon.NProc; // Number of running producers private BoundedBufferMon buf; // Buffer shared with other threads private boolean isrunning = true; Consumer(int identifier, BoundedBufferMon buffer) { myid = identifier; buf = buffer; } // Constructor public void run() { // overrides run method of the Thread class do { String s = (String) buf.get(); System.out.println("C-" + myid + " read: " + s); if (s.equals("stop") RunningP--; // 1 producer stopped } while (RunningP > 0); // assuming 1 consumer; NProc producers } } // Consumer Laszlo Böszörmenyi Computer Networks Processes - 18

19 Bounded buffer User class public class BufUserMon { // Uses bounded buffer, NProc producers, 1 consumer public final static int NProc = 2, NBuf = 8; static public void main(string args[]) { Producer [] p = new Producer [NProc]; BoundedBufferMon buffer = new BoundedBufferMon(NBuf); for (int i = 0; i < NProc; i++) { // Create and fork producers p[i] = new Producer(i, buffer); p[i].start(); } // All share the same buffer Consumer c = new Consumer(0, buffer); c.start(); // Fork cons. for (int i = 0; i < NProc; i++) { // Let run producers try {Thread.sleep(100);} catch(interruptedexception e) {} p[i].stopp(); // Stop and join producers try {p[i].join();} catch(interruptedexception e) {}; } // All producers merged with main thread try {c.join();} catch(interruptedexception e) {}; // Join cons. System.out.println(Thread.currentThread().getName()); } // main } // BufUserMon Starts P-0 Starts P-1 Starts C-0 C-0 read: P-0: C-0 read: P-1: C-0 read: P-0: C-0 read: P-0: C-0 read: P-1: C-0 read: P-0: C-0 read: P-0: C-0 read: P-1: C-0 read: P-0: Stops P-0 C-0 read: P-1: C-0 read: stop C-0 read: P-1: C-0 read: P-1: C-0 read: P-1: Stops P-1 C-0 read: stop Stops C-0 main Laszlo Böszörmenyi Computer Networks Processes - 19

20 Semaphores (E. W. Dijkstra) Operation P to enter and V to exit np: number of completed P operations nv: number of completed V operations IN: initial value Semaphore invariant: np nv + IN If integer s = IN + nv np: s 0 < > should embrace an atomic action P(s) <await s > 0 s = s 1> V(s) <s = s + 1> To a railway station with IN rails, IN trains may drive in. After this, semaphore switches to red. Laszlo Böszörmenyi Computer Networks Processes - 20

21 Implementing Semaphores in Java public class Semaphore { private int s = 1; // Semaphore variable (only P and V allowed) public Semaphore (int InitialValue) { s = InitialValue; } public synchronized void P() { // entry (synchronized atomic method) while (s <= 0) { // Waits as long as s becomes positive try {wait();} catch(interruptedexception e) {}; } // s > 0 is guaranteed s--; s > 0! } CS regained public synchronized void V() { s++; notify(); } // exit (synchronized atomic method) // increments semaphore variable // notifies the first waiting thread } // Semaphore Laszlo Böszörmenyi Computer Networks Processes - 21

22 Bounded buffer with semaphores public class BoundedBufferSem { private int in, out = 0; private Semaphore empty, full, mutex; private Object [] data; public BoundedBufferSem (int size) { // Constructor; size > 0! in = 0; out = 0; data = new Object[size]; empty = new Semaphore(size); full = new Semaphore(0); mutex = new Semaphore(1); } // BoundedBufferSem public Object put () { // not synchr.! empty.p(); mutex.p(); data[in] = d; in = (in + 1) % data.length; mutex.v(); full.v(); } // put public Object get () { // not synchr.! full.p(); mutex.p(); Object d = data[out]; out = (out + 1) % data.length; mutex.v(); empty.v(); return d; } // get Laszlo Böszörmenyi Computer Networks Processes - 22

23 The dining philosophers 5 philosophers are sitting at a table They are thinking and eating in a cycle forever On the table are 5 plates and 5 forks Unfortunately, for eating one needs 2 forks A protocol is required that excludes Deadlock E.g. all philosophers take the left fork and wait for the right one Starvation Two non-neighboring philosophers eat alternating excluding the one between them Either give priority those who wait longer, or let them leave a virtual room after eating A special case for general resource management Laszlo Böszörmenyi Computer Networks Processes - 23

24 Dining philosophers fork management public class Forks { // Free of deadlock, not free from starvation private int N; private int [] forks; // forks[i]: number of available forks for p[i] public Forks (int num) { // At start all forks available N = num; forks = new int [N]; for (int i = 0; i < N; i++) forks[i] = 2; } private int left(int id) { if (id == 0) return N-1; else return (id-1) % N; } private int right(int id) { if (id == N-1) return 0; else return (id+1) % N; } public synchronized void pickup(int id) { // Wait as long as both forks available while (forks[id]!= 2) try {wait();} catch(interruptedexception e) {}; forks[left(id)]--; forks[right(id)]--; } // pickup public synchronized void putdown(int id) { forks[left(id)]++; forks[right(id)]++; notifyall(); // NotifyAll is not fair, therefore starvation possible } // putdown } // Forks Laszlo Böszörmenyi Computer Networks Processes - 24

25 Dining philosophers philosopher threads class Philosopher extends Thread { private int id; private Forks f; private Random rd = new Random(); private boolean isrunning = true; public Philosopher(Forks forks, int processid) { f = forks; id = processid; } public void stopp() { isrunning = false; } public void run() { while (isrunning) { f.pickup(id); System.out.println("Philosopher-" + id + " eating"); try {sleep(rd.nextint(10));} catch(interruptedexception e) {} f.putdown(id); System.out.println("Philosopher-" + id + " thinking"); try {sleep(rd.nextint(100));} catch(interruptedexception e) {} } } // run } // Philosopher Laszlo Böszörmenyi Computer Networks Processes - 25

26 public class ForkUser { final static int N = 5; Dining philosophers user class static public void main(string args[]) { Forks f = new Forks(N); Philosopher [] ph = new Philosopher [N]; for (int i = 0; i < N; i++) { ph[i] = new Philosopher(f, i); ph[i].start(); } try {Thread.sleep(500);} catch(interruptedexception e) {} for (int i = 0; i < N; i++) { ph[i].stopp(); try {ph[i].join();} catch(interruptedexception e) {} } System.out.println("main stops"); } } // ForkUser Philosopher-2 eating Philosopher-2 thinking Philosopher-0 eating Philosopher-0 thinking Philosopher-4 eating Philosopher-4 thinking Philosopher-2 eating Philosopher-2 thinking Philosopher-0 stops Philosopher-4 eating Philosopher-4 thinking Philosopher-3 eating Philosopher-1 stops Philosopher-3 thinking Philosopher-2 stops Philosopher-4 eating Philosopher-4 thinking Philosopher-4 eating Philosopher-4 thinking Philosopher-3 stops Philosopher-4 stops main stops Laszlo Böszörmenyi Computer Networks Processes - 26

27 Dining philosophers with semaphores (1) public class ForksSemD { private Semaphore [] forks; private int N; public ForksSem (int num) { N = num; forks = new Semaphore [N]; for (int i = 0; i < N; i++) forks[i] = new Semaphore(1); // Deadlock and starvation danger // mutex for access to forks[i] // At the beginnig al forks available } int left(int id) {if (id == 0) return N-1; else return (id-1) % N;} int right(int id) {if (id == N-1) return 0; else return (id+1) % N; } public void pickup(int id) { forks[left(id)].p(); forks[right(id)].p(); } // pickup public void putdown(int id) { forks[left(id)].v(); forks[right(id)].v(); } // putdown } // ForksSemD Does it help to make these synchronized? Laszlo Böszörmenyi Computer Networks Processes - 27

28 Dining philosophers with semaphores (2) public class ForksSem { // Neither deadlock nor starvation private Semaphore [] forks; // mutex for access to forks[i] private Semaphore room; private int N; public ForksSem (int num) { // At the beginnig al forks available N = num; forks = new Semaphore [N]; room = new Semaphore(N-1); for (int i = 0; i < N; i++) forks[i] = new Semaphore(1); } int left(int id) {if (id == 0) return N-1; else return (id-1) % N;} int right(int id) {if (id == N-1) return 0; else return (id+1) % N; } public void pickup(int id) { room.p(); forks[left(id)].p(); forks[right(id)].p(); } // pickup public void putdown(int id) { forks[left(id)].v(); forks[right(id)].v(); room.v(); } // putdown } // ForksSem Laszlo Böszörmenyi Computer Networks Processes - 28

29 The readers/writers problem In many applications many reads, few writes Let allow all readers in parallel, but only 1 writer If all processes read, no conflict may arise Cannot be solved by simple mutual exclusion If a process wants to write Wait as long as all readers finished Do not allow new readers to enter Number of active writers is 0 or 1 If it is 1 then the number of active readers is 0 If number of waiting writers > 0 then allow no more new readers to enter Laszlo Böszörmenyi Computer Networks Processes - 29

30 Readers/Writers (1) public interface Reader { public void doread(); } // implement in subclasses public interface Writer { public void dowrite(); } // implement in subclasses public abstract class RW implements Reader, Writer { private int activereaders = 0; // threads reading private int activewriters = 0; // always zero or one private int waitingreaders = 0; // threads waiting to read private int waitingwriters = 0; // same for write public void read() { beforeread(); doread(); afterread(); } // read public void write() { beforewrite(); dowrite(); afterwrite(); } // write // Allow arbitrary many readers // Entry protocol for read // Execute actual read implemented elsewhere // Exit protocol for read // Allow exactly 1 writer // Entry protocol for write // Execute actual write implemented elsewhere // Exit protocol for write Laszlo Böszörmenyi Computer Networks Processes - 30

31 Readers/Writers (2) protected boolean allowreader() { return waitingwriters == 0 && activewriters == 0; protected boolean allowwriter() { return activereaders == 0 && activewriters == 0; } // allowreader } // allowwriter protected synchronized void beforeread() { ++waitingreaders; while (!allowreader()) try { wait(); } catch (InterruptedException ex) {} --waitingreaders; ++activereaders; }// beforeread protected synchronized void afterread() { --activereaders; notifyall(); } // afterread protected synchronized void beforewrite() { ++waitingwriters; while (!allowwriter()) try { wait(); } catch (InterruptedException ex) {} --waitingwriters; ++activewriters; } // beforewrite protected synchronized void afterwrite() { --activewriters; notifyall(); } // afterwrite } // RW Laszlo Böszörmenyi Computer Networks Processes - 31

32 Readers/Writers reader threads class ReaderThread extends Thread { private int count = 0; private Random rd = new Random(); private RW rw_c; private boolean isrunning = true; public ReaderThread (RW rw_control) {rw_c = rw_control; } public void stopp() { isrunning = false; } public void run() { while (isrunning) { rw_c.read(); count++; System.out.println(getName() + "-read: " + count); try {sleep(rd.nextint(10));} catch(interruptedexception e) {} } System.out.println("Reader-"+ getname() + " stops"); } // run } // ReaderThread Laszlo Böszörmenyi Computer Networks Processes - 32

33 Readers/Writers writer threads class WriterThread extends Thread { private int count = 0; private Random rd = new Random(); private RW rw_c; private boolean isrunning = true; public WriterThread (RW rw_control) {rw_c = rw_control; } public void stopp() { isrunning = false; } public void run() { while (isrunning) { rw_c.write(); count++; System.out.println(getName() + "-write: " + count); try {sleep(rd.nextint(100));} catch(interruptedexception e) {} } System.out.println("Writer-"+ getname() + " stops"); } // run } // WriterThread Laszlo Böszörmenyi Computer Networks Processes - 33

34 Readers/Writers user class public class RWUser extends RW { static final int NReaders = 5, NWriters = 2; static int totalreads, totalwrites = 0; public void doread() {totalreads++;} // Overrides abstract read: counts reads public void dowrite() {totalwrites++;} // Overrides abstract write: counts writes static public void main(string args[]) { } } RWUser rw_control = new RWUser(); // Controls access for readers/writers ReaderThread [] r = new ReaderThread [NReaders]; WriterThread [] w = new WriterThread [NWriters]; for (int i = 0; i < NWriters; i++) {w[i] = new WriterThread(rw_control); w[i].start();} for (int i = 0; i < NReaders; i++) {r[i] = new ReaderThread(rw_control); r[i].start(); try {Thread.sleep(500);} catch(interruptedexception e) {} for (int i = 0; i < NWriters; i++) { w[i].stopp(); try { w[i].join(); } catch (InterruptedException ex) {} } for (int i = 0; i < NReaders; i++) { r[i].stopp(); try { r[i].join(); } catch (InterruptedException ex) {} } System.out.println("totalWrites = " + totalwrites); System.out.println("totalReads = " + totalreads); Thread-4-read: 44 Thread-5-read: 46 Thread-6-read: 40 Thread-6-read: 41 totalwrites = 17 totalreads = 212 Laszlo Böszörmenyi Computer Networks Processes - 34

35 Time-outs in Java sleep(t) thread sleeps for t milliseconds and keeps the lock wait(t) thread sleeps for t milliseconds, but lock is released public synchronized void ProcessLoop() { processone(); try {wait(1000);} catch (Exception e) {} processtwo(); } public void ProcessLoop() { synchronized (this) { processone(); } } // lock released // lock regained // lock released manually try {Thread.sleep(1000);} catch (Exception e) {} synchronized (this) { processtwo(); } // lock regained manually Laszlo Böszörmenyi Computer Networks Processes - 35

36 Scheduling (1) Controls state-transitions of a system Assigns resources, such as CPU, disk, network etc. Long-term, middle-term, short-term scheduling From scheduling of complex jobs up to individual threads Process (CPU) scheduling controls ready running which ready process gets the CPU(s) Scheduling points 1. running waiting (e.g. I/O is started) 2. running ready (e.g. Interrupt happened) 3. waiting ready (e.g. end of I/O) 4. termination Non-preemptive Scheduling Scheduling only in cases 1 and 4 Laszlo Böszörmenyi Computer Networks Processes - 36

37 Scheduling (2) Preemptive Scheduling Scheduling in all four scheduling points Threads can be forced to release the CPU (preemption) Time-slicing Every thread gets a certain time quantum If time quantum over: timer interrupt is generated Thread is forced to running ready Fairness Each thread gets its CPU share No thread misses its signal eternally No thread waits in the ready queue eternally Laszlo Böszörmenyi Computer Networks Processes - 37

38 Scheduling in Java Priority scheduling A priority level is assigned to every thread Threads at the highest priority level run first On a certain priority level round-robin (one after the other) Priority can be set dynamically and explicitly Optional preemption and time-slicing Time-slicing is allowed but not mandatory depends on the current JVM (Java Virtual Machine) implementation The following scheduling points are defined anyway wait, sleep, wait on a lock, wait on I/O, yield Laszlo Böszörmenyi Computer Networks Processes - 38

39 Problems of priority scheduling Starvation danger Threads with lower priority never get the CPU Priority inversion If a low priority thread keeps a lock High-priority threads must wait for the same lock A low-priority thread slows down high-priority threads Solution for priority inversion: Thread T 1 with priority p 1 keeps lock L Thread T 2 with priority p 2 > p 1 needs Lock L T 1 inherits priority p 2, until the lock is released After that T 1 regains the (lower) priority p 1 again Priority inheritance is implemented by many JVMs Laszlo Böszörmenyi Computer Networks Processes - 39

40 Implementation of threads Green-thread (user-level) model Scheduling by the JVM Fast (no system calls are needed), easier to port I/O Operations must be non-blocking Native-thread (system-level) model Java-threads are mapped on operating system threads Scheduling is done by the operating system Threads become heavier : Thread-pooling Unused threads are stored in a pool: can be reused Usual implementation on Windows Unix systems (Solaris, Linux) provide generally both models Laszlo Böszörmenyi Computer Networks Processes - 40

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization

More information

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

Two Types of Semaphores

Two Types of Semaphores Two Types of Semaphores Counting semaphore integer value can range over an unrestricted domain. Binary semaphore integer value can range only between 0 and 1; can be simpler to implement. Can implement

More information

Process Management And Synchronization

Process Management And Synchronization Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the

More information

Concept of a process

Concept of a process Concept of a process In the context of this course a process is a program whose execution is in progress States of a process: running, ready, blocked Submit Ready Running Completion Blocked Concurrent

More information

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

More information

Lesson 6: Process Synchronization

Lesson 6: Process Synchronization Lesson 6: Process Synchronization Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization

More information

Interprocess Communication By: Kaushik Vaghani

Interprocess Communication By: Kaushik Vaghani Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the

More information

Concurrency. Chapter 5

Concurrency. Chapter 5 Concurrency 1 Chapter 5 2 Concurrency Is a fundamental concept in operating system design Processes execute interleaved in time on a single processor Creates the illusion of simultaneous execution Benefits

More information

Concurrency: Deadlock and Starvation. Chapter 6

Concurrency: Deadlock and Starvation. Chapter 6 Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other Involve conflicting needs for resources

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other No efficient solution Involve conflicting

More information

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; } Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify http://cs.lth.se/eda040 Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify Klas Nilsson 2016-09-20 http://cs.lth.se/eda040 F4: Monitors: synchronized, wait and

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 1019 L12 Synchronization Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Critical section: shared

More information

Chapter 2 Processes and Threads

Chapter 2 Processes and Threads MODERN OPERATING SYSTEMS Third Edition ANDREW S. TANENBAUM Chapter 2 Processes and Threads The Process Model Figure 2-1. (a) Multiprogramming of four programs. (b) Conceptual model of four independent,

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

CSE Traditional Operating Systems deal with typical system software designed to be:

CSE Traditional Operating Systems deal with typical system software designed to be: CSE 6431 Traditional Operating Systems deal with typical system software designed to be: general purpose running on single processor machines Advanced Operating Systems are designed for either a special

More information

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Remaining Contemplation Questions

Remaining Contemplation Questions Process Synchronisation Remaining Contemplation Questions 1. The first known correct software solution to the critical-section problem for two processes was developed by Dekker. The two processes, P0 and

More information

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14 Bruce Char. All rights reserved by the author. Permission is given to students enrolled in CS361 Spring 2000 to reproduce these notes

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Chapter 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008. CSC 4103 - Operating Systems Spring 2008 Lecture - XII Midterm Review Tevfik Ko!ar Louisiana State University March 4 th, 2008 1 I/O Structure After I/O starts, control returns to user program only upon

More information

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions Chapter 2 Processes and Threads [ ] 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling 85 Interprocess Communication Race Conditions Two processes want to access shared memory at

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

More information

CHAPTER 6: PROCESS SYNCHRONIZATION

CHAPTER 6: PROCESS SYNCHRONIZATION CHAPTER 6: PROCESS SYNCHRONIZATION The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. TOPICS Background

More information

CS3502 OPERATING SYSTEMS

CS3502 OPERATING SYSTEMS CS3502 OPERATING SYSTEMS Spring 2018 Synchronization Chapter 6 Synchronization The coordination of the activities of the processes Processes interfere with each other Processes compete for resources Processes

More information

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T Operating Systems Operating Systems Summer 2017 Sina Meraji U of T More Special Instructions Swap (or Exchange) instruction Operates on two words atomically Can also be used to solve critical section problem

More information

Java Threads. Written by John Bell for CS 342, Spring 2018

Java Threads. Written by John Bell for CS 342, Spring 2018 Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.

More information

Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation

Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation Chapter 2 Processes The Process Model Processes and Threads 2.1 Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling Multiprogramming of four programs Conceptual

More information

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads Concurrency - Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads 1 Introduction Concurrency can occur at four levels: Machine instruction

More information

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

What are they? How do we represent them? Scheduling Something smaller than a process? Threads Synchronizing and Communicating Classic IPC problems

What are they? How do we represent them? Scheduling Something smaller than a process? Threads Synchronizing and Communicating Classic IPC problems Processes What are they? How do we represent them? Scheduling Something smaller than a process? Threads Synchronizing and Communicating Classic IPC problems Processes The Process Model a) Multiprogramming

More information

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28)

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28) Lecture Topics Today: Concurrency (Stallings, chapter 5.1-5.4, 5.7) Next: Exam #1 1 Announcements Self-Study Exercise #5 Project #3 (due 9/28) Project #4 (due 10/12) 2 Exam #1 Tuesday, 10/3 during lecture

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Multitasking / Multithreading system Supports multiple tasks

Multitasking / Multithreading system Supports multiple tasks Tasks and Intertask Communication Introduction Multitasking / Multithreading system Supports multiple tasks As we ve noted Important job in multitasking system Exchanging data between tasks Synchronizing

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

Chapter 6 Process Synchronization

Chapter 6 Process Synchronization Chapter 6 Process Synchronization Cooperating Process process that can affect or be affected by other processes directly share a logical address space (threads) be allowed to share data via files or messages

More information

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico. Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

More information

Synchronization problems with semaphores

Synchronization problems with semaphores Synchronization problems with semaphores Lecture 4 of TDA384/DIT391 (Principles of Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2017/2018 Today

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6. Part Three - Process Coordination Chapter 6: Synchronization 6.1 Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure

More information

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Chapter 6: Synchronization 6.1 Background 6.2 The Critical-Section Problem 6.3 Peterson s Solution 6.4 Synchronization Hardware 6.5 Mutex Locks 6.6 Semaphores 6.7 Classic

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:

More information

OS Structure. User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions. Definition, examples, how it works?

OS Structure. User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions. Definition, examples, how it works? Midterm Review OS Structure User mode/ kernel mode (Dual-Mode) Memory protection, privileged instructions System call Definition, examples, how it works? Other concepts to know Monolithic kernel vs. Micro

More information

OS Structure. User mode/ kernel mode. System call. Other concepts to know. Memory protection, privileged instructions

OS Structure. User mode/ kernel mode. System call. Other concepts to know. Memory protection, privileged instructions Midterm Review OS Structure User mode/ kernel mode Memory protection, privileged instructions System call Definition, examples, how it works? Other concepts to know Monolithic kernel vs. Micro kernel 2

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on Chapter 6: Process Synchronization Operating System Concepts 9 th Edit9on Silberschatz, Galvin and Gagne 2013 Objectives To present the concept of process synchronization. To introduce the critical-section

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies Chapter 2 Processes and Threads Processes The Process Model 2.1 Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling Multiprogramming of four programs Conceptual

More information

PROCESS SYNCHRONIZATION

PROCESS SYNCHRONIZATION PROCESS SYNCHRONIZATION Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization

More information

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

More information

Semaphores INF4140. Lecture 3. 0 Book: Andrews - ch.04 ( ) INF4140 ( ) Semaphores Lecture 3 1 / 34

Semaphores INF4140. Lecture 3. 0 Book: Andrews - ch.04 ( ) INF4140 ( ) Semaphores Lecture 3 1 / 34 Semaphores INF4140 13.09.12 Lecture 3 0 Book: Andrews - ch.04 (4.1-4.4) INF4140 (13.09.12 ) Semaphores Lecture 3 1 / 34 Overview Last lecture: Locks and Barriers (complex techniques) No clear difference

More information

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed

More information

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

CS533 Concepts of Operating Systems. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?

More information

PROCESSES & THREADS. Charles Abzug, Ph.D. Department of Computer Science James Madison University Harrisonburg, VA Charles Abzug

PROCESSES & THREADS. Charles Abzug, Ph.D. Department of Computer Science James Madison University Harrisonburg, VA Charles Abzug PROCESSES & THREADS Charles Abzug, Ph.D. Department of Computer Science James Madison University Harrisonburg, VA 22807 Voice Phone: 540-568-8746; Cell Phone: 443-956-9424 E-mail: abzugcx@jmu.edu OR CharlesAbzug@ACM.org

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 1018 L11 Synchronization Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Multilevel feedback queue:

More information

CIS233J Java Programming II. Threads

CIS233J Java Programming II. Threads CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential

More information

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Synchronization COMPSCI 386

Synchronization COMPSCI 386 Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose

More information

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Processes. Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra

Processes. Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Processes Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Processes Process Concept Process Scheduling Operation on Processes Cooperating Processes Interprocess Communication Process Concept Early

More information

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Process Synchronization, Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Synchronization, Silberschatz, Galvin and Gagne 2009 Outline Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 8: Semaphores, Monitors, & Condition Variables 8.0 Main Points: Definition of semaphores Example of use

More information

Introduction to Operating Systems

Introduction to Operating Systems Introduction to Operating Systems Lecture 4: Process Synchronization MING GAO SE@ecnu (for course related communications) mgao@sei.ecnu.edu.cn Mar. 18, 2015 Outline 1 The synchronization problem 2 A roadmap

More information

Synchronization

Synchronization Synchronization 10-28-2013 Synchronization Coming next: Multithreading in JavaFX (javafx.concurrent) Read: Java Tutorial on concurrency JavaFX Tutorial on concurrency Effective Java, Chapter 9 Project#1:

More information

Process Synchronization

Process Synchronization CSC 4103 - Operating Systems Spring 2007 Lecture - VI Process Synchronization Tevfik Koşar Louisiana State University February 6 th, 2007 1 Roadmap Process Synchronization The Critical-Section Problem

More information

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5 Threads CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5 1 Threads The Thread Model (1) (a) Three processes each with one thread (b) One process with three threads 2 1 The Thread Model (2)

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

Lecture 10: Introduction to Semaphores

Lecture 10: Introduction to Semaphores COMP 150-CCP Concurrent Programming Lecture 10: Introduction to Semaphores Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 19, 2008 Semaphores Semaphores (Dijkstra 1968) are widely

More information

CSE 4/521 Introduction to Operating Systems

CSE 4/521 Introduction to Operating Systems CSE 4/521 Introduction to Operating Systems Lecture 7 Process Synchronization II (Classic Problems of Synchronization, Synchronization Examples) Summer 2018 Overview Objective: 1. To examine several classical

More information

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

Synchronization Principles

Synchronization Principles Synchronization Principles Gordon College Stephen Brinton The Problem with Concurrency Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms

More information

Sections 01 (11:30), 02 (16:00), 03 (8:30) Ashraf Aboulnaga & Borzoo Bonakdarpour

Sections 01 (11:30), 02 (16:00), 03 (8:30) Ashraf Aboulnaga & Borzoo Bonakdarpour Course CS350 - Operating Systems Sections 01 (11:30), 02 (16:00), 03 (8:30) Instructor Ashraf Aboulnaga & Borzoo Bonakdarpour Date of Exam October 25, 2011 Time Period 19:00-21:00 Duration of Exam Number

More information