Process Synchroniza/on
|
|
- Mitchell Wilkins
- 5 years ago
- Views:
Transcription
1 Process Synchroniza/on Andrew Case Slides adapted from Mohamed Zahran, Clark Barre9, Jinyang Li, Randy Bryant and Dave O Hallaron
2 Topics Sharing data Race condi/ons Mutual exclusion and semaphores Sample problems Deadlocks
3 Mul/Threaded process A process can have mul/ple threads Each thread has its own logical control flow (PC, registers, etc.) Each thread shares the same code, data, and kernel context Shared code and data Thread (main thread) stack shared libraries Thread (peer thread) stack Thread context: Data registers Condition codes SP PC run-time heap read/write data read-only code/data Kernel context: VM structures Descriptor table brk pointer Thread context: Data registers Condition codes SP PC 3
4 Threads Memory Model Conceptual model: MulMple threads run within the context of a single process Each thread has its own separate thread context Thread ID, stack, stack pointer, PC, condimon codes, and GP registers All threads share the remaining process context Code, data, heap, and shared library segments of the process virtual address space Open files and installed handlers Opera/onally, this model is not strictly enforced: Register values are protected, but Any thread can read and write to enmre virtual address space (any threads stack) 4
5 Mapping Variable Instances to Memory Global variables Def: Variable declared outside of a funcmon Virtual memory contains exactly one instance of any global variable Local variables Def: Variable declared inside funcmon without static a9ribute Each thread stack contains one instance of each local variable Local sta/c variables Def: Variable declared inside funcmon with the static a9ribute Virtual memory contains exactly one instance of any local sta/c variable. 5
6 Mapping Variable Instances to Memory Global var: instance in data memory Local vars: instance in main thread stack linux>./a.out []: Hello from foo (cnt=) []: Hello from foo (cnt=) char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; Local var: instances ( myid in peer thread s stack, myid in peer thread s stack ) /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); Local sta-c var: instance in data memory 6
7 Problem: Race condi/ons A race condi-on occurs when correctness of the program depends on one thread or process reaching point x before another thread or process reaches point y Any ordering of instruc/ons from mul/ple threads may occur race.c 7
8 Race Condi/on: Example How can we fix it? int main() { int cnt; for (cnt = ; cnt < ; cnt++) { /* send an cnt to each thread */ pthread_create(&tid, NULL, thread, &cnt); void *thread(void *p) { int i = *((int *)p); /* cast to an int ptr and de-ref */ pthread_detach(pthread_self()); save_value(i); /* do something with the count */ return NULL; Race Test If no race, then each thread would get different value of cnt Set of saved values would consist of one copy each of through 99. 8
9 Race Condi/on: Example :int cnt; :for (cnt = ; cnt < ; cnt++) { 3: pthread_create(&tid, NULL, thread, &cnt); 4: 5:void *thread(void *p) { 6: int i = *((int *)p); 7: pthread_detach(pthread_self()); 8: save_value(i); 9: return NULL; : Line of code run Main thread Worker thread i (in thread) cnt Problem: i in worker thread should have been set to 9
10 Experimental Results No Race Single core laptop Mul/core server (Number of /mes each value is saved) The race can really happen!
11 Race Condi/on: Fixed! int main() { int cnt; for (cnt = ; cnt < ; cnt++) { int *j = malloc(sizeof(int)); /* create separate var */ *j = cnt; /* for each thread */ pthread_create(&tid, NULL, thread, j); void *thread(void *p) { int i = *((int *)p); free(p); /* free it when done */ pthread_detach(pthread_self()); save_value(i); return NULL;
12 Race Condi/on: Problem : int cnt; : for (cnt = ; cnt < ; cnt++) { 3: int *j = malloc(sizeof(int)); 4: *j = cnt; 5: pthread_create(&tid, NULL, thread, j); 6: Line of code 3 Main thread Worker thread i Cnt (worker)(global) *j? *p 7: void *thread(void *p) { 8: int i = *((int *)p); 9: free(p); : pthread_detach(pthread_self()); : save_value(i); : return NULL; 3:
13 Topics Sharing data Race condi/ons Mutual exclusion and Semaphores Sample problems Deadlocks 3
14 Improper Synchroniza/on: badcnt.c volatile int cnt = ; /* global */ int main(int argc, char **argv) { int niters = atoi(argv[]); pthread_t tid, tid; pthread_create(&tid, NULL, thread, &niters); pthread_create(&tid, NULL, thread, &niters); pthread_join(tid, NULL); pthread_join(tid, NULL); /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%d\n, cnt); else printf("ok cnt=%d\n", cnt); exit(); /* Thread routine */ void *thread(void *vargp) { /* local data */ int i; int niters = *((int *)vargp); for (i = ; i < niters; i++) cnt++; /* shared data */ return NULL; linux>./badcnt OK cnt= linux>./badcnt BOOM! cnt=35 linux> cnt should equal,. What went wrong? 4
15 Assembly Code for Counter Loop C code for counter loop in thread i for (i=; i < niters; i++) cnt++; /* changing shared data */ Corresponding assembly code.l: movl (%rdi),%ecx movl $,%edx cmpl %ecx,%edx jge.l3 Head (loop itera/on) Cri/cal Regions: changing shared data movl cnt(%rip),%eax incl %eax movl %eax,cnt(%rip) Load cnt Update cnt Store cnt.l3: incl %edx cmpl %ecx,%edx jl.l Tail (loop itera/on) 5
16 Concurrent Execu/on Any sequen/ally consistent interleaving is possible X i denotes that thread i executes instrucmon X %eax i is the content of %eax in thread i s context Thread cri/cal sec/on i (thread) instr i %eax %eax cnt H L U S H L U S T T OK Thread cri/cal sec/on H head L Load U Update S Store T tail 6
17 Concurrent Execu/on (cont) Race condi/on: two threads increment the counter, but the result is instead of i (thread) instr i %eax %eax cnt H L U H L S T U S T Oops! Thread cri/cal sec/on Thread cri/cal sec/on H head L Load U Update S Store T tail 7
18 Concurrent Execu/on (cont) How about this ordering? i (thread) instr i %eax %eax cnt H L H L U S U S T T How do we fix it?! Oops! Thread cri/cal sec/on Thread cri/cal sec/on H head L Load U Update S Store T tail 8
19 Enforcing Mutual Exclusion Answer: We must synchronize the execu/on of the threads so that cri/cal regions are run sequen/ally. i.e., need to guarantee mutually exclusive access to crimcal regions Classic solu/on: Semaphores (Dijkstra) Other approaches (out of our scope) Pthread Mutexes and condimon variables Monitors (Java) 9
20 Semaphores Semaphore: nonnega/ve global integer synchroniza/on variable Manipulated by P and V opera/ons: P(s): [ while (s == ) wait(); s--; ] Dutch for "Proberen" (test) Used to gain access to a shared resource AKA: down, wait V(s): [ s++; ] Dutch for "Verhogen" (increment) Used to release access of a shared resource AKA: up, post [ ] indicates an atomic opera/on performed by the OS Guarantees these are run as if it was one instrucmons Only one P or V operamon at a Mme can modify s.
21 Using Semaphores for Mutual Exclusion Basic idea: Associate a unique semaphore mutex with each shared resource (e.g. a variable) Surround corresponding crimcal secmons with P(mutex)/wait() and V(mutex)/post() operamons. Terminology: Binary semaphore: semaphore whose value is always or Mutex: binary semaphore used for mutual exclusion P()/wait() operamon: locking the mutex V()/post() operamon: unlocking or releasing the mutex Holding a mutex/resource: locked and not yet unlocked.
22 C Semaphore Opera/ons Pthreads func/ons: #include <semaphore.h> shared between threads (as opposed to processes) /* creating a semaphore */ int sem_init(sem_t *sem,, unsigned int val); /* s = val */ /* using a semaphore */ int sem_wait(sem_t *sem); /* P(s): try to claim a resource */ int sem_post(sem_t *sem); /* V(s): release a resource */ Number of resources available (how many threads can access the data at any given /me)
23 Improper Synchroniza/on: badcnt.c volatile int cnt = ; /* global */ int main(int argc, char **argv) { int niters = atoi(argv[]); pthread_t tid, tid; pthread_create(&tid, NULL, thread, &niters); pthread_create(&tid, NULL, thread, &niters); pthread_join(tid, NULL); pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp) { /* local data */ int i, niters = *((int *)vargp); for (i = ; i < niters; i++) cnt++; /* shared data */ return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%d\n, cnt); else printf("ok cnt=%d\n", cnt); exit(); How can we fix this using semaphores? 3
24 Proper Synchroniza/on: goodcnt.c Define and ini/alize a mutex for the shared variable cnt: volatile int cnt = ; /* Counter */ sem_t mutex; /* Semaphore that protects cnt */ sem_init(&mutex,, ); /* mutex= (only access at a time) */ Surround cri/cal sec/on with P and V: for (i = ; i < niters; i++) { sem_wait(&mutex); /* P() */ cnt++; sem_post(&mutex); /* V() */ linux>./goodcnt OK cnt= linux>./goodcnt OK cnt= linux> Note: much slower than badcnt.c 4
25 Sample Problems Readerswriters problem Producerconsumer problem 5
26 ReadersWriters Problem Problem statement: Reader threads only read the object Writer threads modify the object Writers must have exclusive access to the object Unlimited number of readers can access the object Examples: Online airline reservamon system MulMthreaded caching Web proxy Banking somware 6
27 Variants of ReadersWriters First readerswriters problem (favors readers) No reader should be kept waimng unless a writer has already been granted permission to use the object. A reader that arrives amer a waimng writer gets priority over the writer. Second readerswriters problem (favors writers) Once a writer is ready to write, it performs its write as soon as possible A reader that arrives amer a writer must wait, even if the writer is also waimng. Starva-on (where a thread waits indefinitely) is possible in both cases. 7
28 Solu/on to First ReadersWriters Problem Readers: int readcnt; /* Initially */ sem_t mutex, w; /* Both set to */ void reader(void) { while () { /* am I the first reader in? */ /* if so, try to lock mutex */ /* to exclude writer */ /* do some reading */ void writer(void) { while () { /* try to lock mutex */ /* to exclude readers */ Writers: /* do some writing */ /* unlock mutex */ /* am I the last reader out? */ /* if so, unlock mutex */ 8
29 Solu/on to First ReadersWriters Problem Readers: int readcnt; /* Initially */ sem_t mutex, w; /* Both initially */ void reader(void) { while () { sem_wait(&mutex); readcnt++; if (readcnt == ) /* First in */ sem_wait(&w); sem_post(&mutex); /* Reading happens here */ Writers: void writer(void) { while () { sem_wait(&w); /* Writing here */ sem_post(&w); rw.c sem_wait(&mutex); readcnt--; if (readcnt == ) /* Last out */ sem_post(&w); sem_post(&mutex); 9
30 Sample Problems Readerswriters problem Producerconsumer problem 3
31 ProducerConsumer Problem producer thread shared buffer consumer thread Common synchroniza/on pamern: Producer waits for empty slot, inserts item in buffer, and nomfies consumer Consumer waits for item, removes it from buffer, and nomfies producer Examples MulMmedia processing: Producer creates MPEG video frames, consumer renders them Eventdriven graphical user interfaces Producer detects mouse clicks, mouse movements, and keyboard hits and inserts corresponding events in buffer Consumer retrieves events from buffer and paints the display 3
32 ProducerConsumer on element Buffer #include csapp.h #define NITERS 5 void *producer(void *arg); void *consumer(void *arg); struct { int buf; /* shared var */ sem_t full; /* sems */ sem_t empty; shared; int main() { pthread_t tid_producer; pthread_t tid_consumer; /* Initialize the semaphores */ sem_init(&shared.empty,, ); sem_init(&shared.full,, ); /* Create threads and wait */ pthread_create(&tid_producer, NULL, producer, NULL); pthread_create(&tid_consumer, NULL, consumer, NULL); pthread_join(tid_producer, NULL); pthread_join(tid_consumer, NULL); exit(); 3
33 ProducerConsumer on element Buffer Ini/ally: empty==, full== Producer Thread void *producer(void *arg) { int i, item; Consumer Thread void *consumer(void *arg) { int i, item; for (i = ; i < NITERS; i++) { /* Produce item */ item = i; printf("produced %d\n, item); /* Write item to buf */ sem_wait(&shared.empty); shared.buf = item; sem_post(&shared.full); return NULL; for (i = ; i < NITERS; i++) { /* Read item from buf */ sem_wait(&shared.full); item = shared.buf; sem_post(&shared.empty); /* Consume item */ printf("consumed %d\n, item); return NULL; 33
34 ProducerConsumer on an nelement Buffer Requires a mutex and two coun/ng semaphores: mutex: enforces mutually exclusive access to the the buffer slots: counts the available slots in the buffer items: counts the available items in the buffer Implemented using a shared buffer 34
35 ProducerConsumer w/ Shared Buffer Producerconsumer pamern: Producer inserts item in buffer (waits if buffer is full) Consumer removes item from buffer (waits if buffer is empty) Producer Producer threads Producer threads threads Shared Buffer Producer Producer threads Producer threads threads Examples: Network server Producer threads read from sockets and put client request on buffer Consumer threads process clients requests from buffer 35
36 Topics Sharing data Race condi/ons Mutual exclusion and semaphores Sample problems Deadlocks 36
37 Problem: Deadlocks Def: A process is deadlocked if it is wai/ng for a condi/on that will never be occur. Typical Scenario Processes and Process both need the same two resources (A and B) Process acquires A, waits for B Process acquires B, waits for A Both will wait forever! 37
38 Deadlocking With Semaphores int main() { pthread_t tid[]; sem_init(&mutex[],, ); /* mutex[] = */ sem_init(&mutex[],, ); /* mutex[] = */ pthread_create(&tid[], NULL, worker, (void*) ); /* Lock - */ pthread_create(&tid[], NULL, worker, (void*) ); /* Lock - */ pthread_join(tid[], NULL); pthread_join(tid[], NULL); exit(); void *worker(void *x) { int id = (int) x; sem_wait(&mutex[id]); sem_wait(&mutex[-id]); // Do something sem_post(&mutex[id]); sem_post(&mutex[-id]); return NULL; Tid[]: P(s ); P(s ); V(s ); V(s ); Tid[]: P(s ); P(s ); V(s ); V(s ); 38
39 Avoiding Deadlock with Semaphores Acquire shared resources in same order Release resources in same reverse order int main() { pthread_t tid[]; sem_init(&mutex[],, ); /* mutex[] = */ sem_init(&mutex[],, ); /* mutex[] = */ pthread_create(&tid[], NULL, worker, (void*) ); /* Lock - */ pthread_create(&tid[], NULL, worker, (void*) ); /* Lock - */ pthread_join(tid[], NULL); pthread_join(tid[], NULL); exit(); void *worker(void *x) { int id = (int) x; sem_wait(&mutex[id]); sem_wait(&mutex[-id]); // Do something sem_post(&mutex[id]); sem_post(&mutex[-id]); return NULL; Tid[]: P(s ); P(s ); V(s ); V(s ); Tid[]: P(s ); P(s ); V(s ); V(s ); 39
40 Threads Summary Threads are were growing in popularity Pros: Somewhat cheaper than processes Easy to share data between threads Cons: Easy to share data between threads Easy to introduce subtle synchronizamon errors Shares variables must be protected to ensure mutually exclusive access Semaphores provide one solumon 4
Today. Threads review Sharing Mutual exclusion Semaphores
SYNCHRONIZATION Today Threads review Sharing Mutual exclusion Semaphores Process: Traditional View Process = process context + code, data, and stack Process context Program context: Data registers Condition
More informationSynchronization: Basics
Synchronization: Basics 53: Introduction to Computer Systems 4 th Lecture, April 8, 7 Instructor: Seth Copen Goldstein, Franz Franchetti Today Threads review Sharing Mutual exclusion Semaphores Traditional
More informationCarnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition
Synchronization: Basics 53: Introduction to Computer Systems 4 th Lecture, November 6, 7 Instructor: Randy Bryant Today Threads review Sharing Mutual exclusion Semaphores 3 Traditional View of a Process
More informationSynchronization: Basics
Synchronization: Basics CS 485G6: Systems Programming Lecture 34: 5 Apr 6 Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared? The answer is not as simple
More informationCarnegie Mellon Concurrency and Synchronization
Concurrency and Synchronization CMPSCI 3: Computer Systems Principles int pthread_join (pthread_t thread, void **value_ptr) { int result; ptw3_thread_t * tp = (ptw3_thread_t *) thread.p; if (NULL == tp
More informationCarnegie Mellon. Synchroniza+on : Introduc+on to Computer Systems Recita+on 14: November 25, Pra+k Shah (pcshah) Sec+on C
Synchroniza+on 15-213: Introduc+on to Computer Systems Recita+on 14: November 25, 2013 Pra+k Shah (pcshah) Sec+on C 1 Topics News Shared State Race condi+ons Synchroniza+on Mutex Semaphore Readers- writers
More informationProgramming with Threads Dec 7, 2009"
Programming with Threads Dec 7, 2009" Administrivia" 2! Shared Variables in Threaded C Programs" 3! Threads Memory Model" 4! Example of Threads Accessing Another Threadʼs Stack" char **ptr; /* global */
More informationShared Variables in Threaded C Programs. Systemprogrammering Föreläsning 11 Programming with Threads
Systemprogrammering Föreläsning Programming with Threads Topics Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared variables?! The answer is not as simple
More informationSynchronization: Advanced
Synchronization: Advanced CS 485G-006: Systems Programming Lecture 35: 27 Apr 2016 1 Enforcing Mutual Exclusion Question: How can we guarantee a safe trajectory? Answer: We must synchronize the execution
More informationfor (i = 0; i < 2; i++)
53 The course that gives CMU its Zip! Programming with Threads Dec 5, Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races and deadlocks
More information! What is the memory model for threads? ! How are variables mapped to memory instances? ! How many threads reference each of these instances?
53 The course that gives CMU its Zip! Programming with Threads Dec 5, Topics! Shared variables! The need for synchronization! Synchronizing with semaphores! Thread safety and reentrancy! Races and deadlocks
More informationSynchronization April 29, 2008
5-3 The course that gives CMU its Zip! Synchronization April 9, 008 Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races and deadlocks class5.ppt
More informationLecture #24 Synchronization
Lecture #24 Synchronization 8-600: Foundations of Computer Systems November 27, 207 Today Sharing Mutual exclusion Semaphores 2 Shared Variables in Threaded C Programs Question: Which variables in a threaded
More informationCarnegie Mellon Synchronization: Advanced
1 Synchronization: Advanced 15-213 / 18-213: Introduction to Computer Systems 25 th Lecture, Nov. 20, 2018 2 Reminder: Semaphores Semaphore: non-negative global integer synchronization variable Manipulated
More informationIntroduction to Threads
Computer Systems Introduction to Threads Race Conditions Single- vs. Multi-Threaded Processes Process Process Thread Thread Thread Thread Memory Memory Heap Stack Heap Stack Stack Stack Data Data Code
More informationCS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio
CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio Fall 2017 1 Outline Inter-Process Communication (20) Threads
More informationThe course that gives CMU its Zip! Concurrency II: Synchronization Nov 14, 2000
5-3 The course that gives CMU its Zip! Concurrency II: Synchronization Nov 4, 000 Topics Progress graphs Semaphores Mutex and condition variables Barrier synchronization Timeout waiting A version of badcnt.c
More informationProgramming with Threads
Programming with Threads Ref: Computer Systems: A Programmer's Perspective, Bryant and O'Hallaron, First edition, Pearson Education 2003 Topics Shared variables The need for synchronization Synchronizing
More informationCS3733: Operating Systems
Outline CS3733: Operating Systems Topics: Synchronization, Critical Sections and Semaphores (SGG Chapter 6) Instructor: Dr. Tongping Liu 1 Memory Model of Multithreaded Programs Synchronization for coordinated
More informationCSC 1600: Chapter 6. Synchronizing Threads. Semaphores " Review: Multi-Threaded Processes"
CSC 1600: Chapter 6 Synchronizing Threads with Semaphores " Review: Multi-Threaded Processes" 1 badcnt.c: An Incorrect Program" #define NITERS 1000000 unsigned int cnt = 0; /* shared */ int main() pthread_t
More informationUsing Semaphores CS 241. March 14, University of Illinois
Using Semaphores CS 241 March 14, 2012 University of Illinois Slides adapted in part from material accompanying Bryant & O Hallaron, Computer Systems: A Programmer's Perspective, 2/E 1 Announcements MP6
More informationConcurrent Programming
Concurrent Programming 15-213 / 18-213: Introduc2on to Computer Systems 23 rd Lecture, Nov. 14, 2013 Instructors: Randy Bryant, Dave O Hallaron, and Greg Kesden 1 Concurrent Programming is Hard! The human
More informationConcurrency on x86-64; Threads Programming Tips
Concurrency on x86-64; Threads Programming Tips Brad Karp UCL Computer Science CS 3007 22 nd March 2018 (lecture notes derived from material from Eddie Kohler, David Mazières, Phil Gibbons, Dave O Hallaron,
More informationSynchroniza+on II COMS W4118
Synchroniza+on II COMS W4118 References: Opera+ng Systems Concepts (9e), Linux Kernel Development, previous W4118s Copyright no2ce: care has been taken to use only those web images deemed by the instructor
More informationCarnegie Mellon Performance of Mul.threaded Code
Performance of Mul.threaded Code Karen L. Karavanic Portland State University CS 410/510 Introduc=on to Performance Spring 2017 1 Using Selected Slides from: Concurrent Programming 15-213: Introduc=on
More informationCS 3723 Operating Systems: Final Review
CS 3723 Operating Systems: Final Review Outline Threads Synchronizations Pthread Synchronizations Instructor: Dr. Tongping Liu 1 2 Threads: Outline Context Switches of Processes: Expensive Motivation and
More informationConcurrent Programming
Concurrent Programming 15-213: Introduc0on to Computer Systems 22 nd Lecture, Nov. 11, 2010 Instructors: Randy Bryant and Dave O Hallaron 1 Concurrent Programming is Hard! The human mind tends to be sequen9al
More informationCondition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois
Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:
More informationSynchroniza+on: Advanced
Synchroniza+on: Advanced 15-213: Introduc;on to Computer Systems 25 th Lecture, Nov. 24, 2015 Instructors: Randal E. Bryant and David R. O Hallaron 1 Review: Semaphores Semaphore: non- nega+ve global integer
More informationConcurrent Programming
Concurrent Programming Andrew Case Slides adapted from Mohamed Zahran, Jinyang Li, Clark Barre=, Randy Bryant and Dave O Hallaron 1 Concurrent vs. Parallelism Concurrency: At least two tasks are making
More informationNote: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer Problem.
CSCI-375 Operating Systems Lab #5 Semaphores, Producer/Consumer Problem October 19, 2016 Note: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer
More informationConcurrent programming
Concurrent programming : Introduc2on to Computer Systems 24th Lecture Sec2ons 12.1-12.3 Instructors: Ian Foster Gordon Kindlmann Slides borrow copiously from materials by Randy Bryant and Dave O Hallaron
More informationThe course that gives CMU its Zip! Concurrency I: Threads April 10, 2001
15-213 The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing data
More informationConcurrent Programming is Hard! Concurrent Programming. Reminder: Iterative Echo Server. The human mind tends to be sequential
Concurrent Programming is Hard! Concurrent Programming 15 213 / 18 213: Introduction to Computer Systems 23 rd Lecture, April 11, 213 Instructors: Seth Copen Goldstein, Anthony Rowe, and Greg Kesden The
More informationCS 5523: Operating Systems
CS 5523: Operating Systems Instructor: Dr. Tongping Liu Midterm Exam: Oct 6, 2015, Tuesday 7:15pm 8:30pm CS5523: Operating Systems @ UTSA 1 Lecture1: OS Overview Operating System: what is it?! Evolution
More informationConcurrent Programming
Concurrent Programming CS 485G-006: Systems Programming Lectures 32 33: 18 20 Apr 2016 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking
More informationLecture #23 Concurrent Programming
Lecture #23 Concurrent Programming Nov. 20, 2017 18-600 Foundations of Computer Systems 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking
More informationMultithreading Programming II
Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure
More informationCS 5523 Operating Systems: Thread and Implementation
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationCarnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition
Carnegie Mellon 1 Concurrent Programming 15-213: Introduction to Computer Systems 23 rd Lecture, Nov. 13, 2018 2 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time
More informationSynchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks
Synchronization II Today Condition Variables Semaphores Monitors and some classical problems Next time Deadlocks Condition variables Many times a thread wants to check whether a condition is true before
More informationTotal Score is updated. The score of PA4 will be changed! Please check it. Will be changed
Announcement Total Score is updated Please check it Will be changed The score of PA4 will be changed! 1 Concurrent Programming Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Sanghoon Han(sanghoon.han@csl.skku.edu)
More informationComputer Systems Laboratory Sungkyunkwan University
Concurrent Programming Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int main (int argc, char *argv[]) {... listenfd = socket(af_inet, SOCK_STREAM, 0); bzero((char
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),
More informationConcurrent Programming
Concurrent Programming Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int
More informationCS Operating Systems: Threads (SGG 4)
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationConcurrent Programming
Concurrent Programming Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu
More informationThreads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr.
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution
More informationThread. Disclaimer: some slides are adopted from the book authors slides with permission 1
Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast
More informationRecitation 14: Proxy Lab Part 2
Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization 2 ProxyLab ProxyLab is due in 1 week. No grace days Late days allowed (-15%) Make sure to submit
More informationApproaches to Concurrency
PROCESS AND THREADS Approaches to Concurrency Processes Hard to share resources: Easy to avoid unintended sharing High overhead in adding/removing clients Threads Easy to share resources: Perhaps too easy
More informationCSE Opera,ng System Principles
CSE 30341 Opera,ng System Principles Synchroniza2on Overview Background The Cri,cal-Sec,on Problem Peterson s Solu,on Synchroniza,on Hardware Mutex Locks Semaphores Classic Problems of Synchroniza,on Monitors
More informationConcurrent Servers Dec 2, 2009"
Concurrent Servers Dec 2, 2009" Administrivia" 2! Iterative Servers" client 1! server! client 2! call connect ret connect call read ret read close call accept" ret accept" write close call accept" ret
More informationANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT
ANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT Due date: 08.05.2013 Lab Hours You re expected to implement Producer-Consumer Problem that is described below. (Any form of cheating
More informationSynchronization II. q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks
Synchronization II q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks Condition variables Locks are not enough to build concurrent programs Many times a thread
More informationCS 3305 Intro to Threads. Lecture 6
CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform
More informationCS333 Intro to Operating Systems. Jonathan Walpole
CS333 Intro to Operating Systems Jonathan Walpole Threads & Concurrency 2 Threads Processes have the following components: - an address space - a collection of operating system state - a CPU context or
More informationConcurrent Programming
Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently
More information[537] Semaphores. Tyler Harter
[537] Semaphores Tyler Harter Producer/Consumer Problem Producers generate data (like pipe writers). Consumers grab data and process it (like pipe readers). Producer/consumer problems are frequent in systems.
More informationProxy: Concurrency & Caches
Proxy: Concurrency & Caches Elie Krevat (with wisdom from past terms) Outline Proxy Lab logistics Concurrency and multi-threading Synchronization with semaphores Caching objects in your proxy Proxy Lab
More informationcall connect call read call connect ret connect call fgets Client 2 blocks waiting to complete its connection request until after lunch!
15-213 The course that gives CMU its Zip! Concurrent Servers December 4, 2001 Topics Limitations of iterative servers Process-based concurrent servers Threads-based concurrent servers Event-based concurrent
More informationCS345 Opera,ng Systems. Φροντιστήριο Άσκησης 2
CS345 Opera,ng Systems Φροντιστήριο Άσκησης 2 Inter- process communica0on Exchange data among processes Methods Signals Pipes Sockets Shared Memory Sockets Endpoint of communica,on link between two programs
More informationCS 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 informationRecitation 14: Proxy Lab Part 2
Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization PXYDRIVE Demo 2 ProxyLab Checkpoint is worth 1%, due Thursday, Nov. 29 th Final is worth 7%, due
More informationW4118 Operating Systems. Instructor: Junfeng Yang
W4118 Operating Systems Instructor: Junfeng Yang Outline Semaphores Producer-consumer problem Monitors and condition variables 2 Semaphore motivation Problem with lock: mutual exclusion, but no ordering
More informationConcept 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 informationSemaphores Semaphores: A Definition
23 Semaphores As we know now, one needs both locks and condition variables to solve a broad range of relevant and interesting concurrency problems. The first person who realized this years ago was Edsger
More informationConcurrent Programming
Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently
More informationCS510 Operating System Foundations. Jonathan Walpole
CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking
More informationConcurrency. Alan L. Cox Some slides adapted from CMU slides
Concurrency Alan L. Cox alc@rice.edu Some slides adapted from CMU 15.213 slides Objectives Be able to apply three techniques for achieving concurrency Process Thread Event-driven Be able to analyze the
More informationThreading Language and Support. CS528 Multithreading: Programming with Threads. Programming with Threads
Threading Language and Support CS528 Multithreading: Programming with Threads A Sahu Dept of CSE, IIT Guwahati Pthread: POSIX thread Popular, Initial and Basic one Improved Constructs for threading c++
More informationConcurrent Programming. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Concurrent Programming Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int main (int argc, char *argv[]) {... listenfd = socket(af_inet,
More informationLocks and semaphores. Johan Montelius KTH
Locks and semaphores Johan Montelius KTH 2018 1 / 40 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;
More informationOpera&ng Systems ECE344
Opera&ng Systems ECE344 Lecture 6: Synchroniza&on (II) Semaphores and Monitors Ding Yuan Higher- Level Synchroniza&on We looked at using locks to provide mutual exclusion Locks work, but they have some
More informationDealing 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 informationPRINCIPLES OF OPERATING SYSTEMS
Department of Computer Science, University of Calgary PRINCIPLES OF OPERATING SYSTEMS Tutorial 9/10: Concurrency CPSC 457, Spring 2015 June 1-2, 2015 Announcement Midterm exam is rescheduled. The exam
More informationData Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017
Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread
More informationConcurrent Programming April 21, 2005
15-213 The course that gives CMU its Zip! Concurrent Programming April 21, 2005 Topics Limitations of iterative servers Process-based concurrent servers Event-based concurrent servers Threads-based concurrent
More informationAnnouncements. Class feedback for mid-course evaluations Receive about survey to fill out until this Friday
Announcements Project 2: Part 2a will be graded this week Part 2b take longer since we compare all graphs Project 3: Shared memory segments Linux: use shmget and shmat across server + client processes
More informationSemaphores. 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 informationWhat is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.
What is concurrency? Concurrency Johan Montelius KTH 2017 Concurrency: (the illusion of) happening at the same time. A property of the programing model. Why would we want to do things concurrently? What
More informationThread Coordination -Managing Concurrency
Thread Coordination -Managing Concurrency David E. Culler CS162 Operating Systems and Systems Programming Lecture 8 Sept 17, 2014 h
More informationOperating 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 informationTCSS 422: OPERATING SYSTEMS
TCSS 422: OPERATING SYSTEMS OBJECTIVES Introduction to threads Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma Race condition Critical section Thread
More informationCS533 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 informationConcurrency. Johan Montelius KTH
Concurrency Johan Montelius KTH 2017 1 / 32 What is concurrency? 2 / 32 What is concurrency? Concurrency: (the illusion of) happening at the same time. 2 / 32 What is concurrency? Concurrency: (the illusion
More informationrecap, what s the problem Locks and semaphores Total Store Order Peterson s algorithm Johan Montelius 0 0 a = 1 b = 1 read b read a
recap, what s the problem Locks and semaphores Johan Montelius KTH 2017 # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++; int main
More informationIV. Process Synchronisation
IV. Process Synchronisation Operating Systems Stefan Klinger Database & Information Systems Group University of Konstanz Summer Term 2009 Background Multiprogramming Multiple processes are executed asynchronously.
More informationCS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives
CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives Jonathan Walpole Computer Science Portland State University 1 What does a typical thread API look
More informationKING FAHD UNIVERSITY OF PETROLEUM & MINERALS. Information and Computer Science Department. ICS 431 Operating Systems. Lab # 9.
KING FAHD UNIVERSITY OF PETROLEUM & MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 9 Semaphores Objectives: In this lab, we will use semaphore to solve various synchronization
More informationThree Basic Mechanisms for Creating Concurrent Flows. Systemprogrammering 2009 Föreläsning 10 Concurrent Servers. Process-Based Concurrent Server
Systemprogrammering 2009 Föreläsning 10 Concurrent Servers Topics! Limitations of iterative servers! Process-based concurrent servers! Event-based concurrent servers! Threads-based concurrent servers Three
More informationSynchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han
Synchronization CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Announcements HW #3 is coming, due Friday Feb. 25, a week+ from now PA #2 is coming, assigned about next Tuesday Midterm is tentatively
More informationCSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks
CSci 4061 Introduction to Operating Systems Synchronization Basics: Locks Synchronization Outline Basics Locks Condition Variables Semaphores Basics Race condition: threads + shared data Outcome (data
More informationAn Introduction to Parallel Systems
Lecture 4 - Shared Resource Parallelism University of Bath December 6, 2007 When Week 1 Introduction Who, What, Why, Where, When? Week 2 Data Parallelism and Vector Processors Week 3 Message Passing Systems
More informationOperating Systems. Thread Synchronization Primitives. Thomas Ropars.
1 Operating Systems Thread Synchronization Primitives Thomas Ropars thomas.ropars@univ-grenoble-alpes.fr 2017 2 Agenda Week 42/43: Synchronization primitives Week 44: Vacation Week 45: Synchronization
More informationConcurrent Programming November 28, 2007
15-213 Concurrent Programming November 28, 2007 Topics Limitations of iterative servers Process-based concurrent servers Event-based concurrent servers Threads-based concurrent servers class25.ppt Concurrent
More informationCS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control
Processes & Threads Concurrent Programs Process = Address space + one thread of control Concurrent program = multiple threads of control Multiple single-threaded processes Multi-threaded process 2 1 Concurrent
More informationIterative Servers The course that gives CMU its Zip! Iterative servers process one request at a time. Concurrent Servers
15-213 The course that gives CMU its Zip! Concurrent Servers Dec 3, 2002 Topics! Limitations of iterative servers! Process-based concurrent servers! Event-based concurrent servers! Threads-based concurrent
More informationExample. Example. Threading Language and Support. CS528 Multithreading: Programming with Threads. The boss/worker model. Thread Programming models
Threading Language and Support CS528 Multithreading: Programming with Threads A Sahu Dept of CSE, IIT Guwahati Pthread: POSIX thread Popular, Initial and Basic one Improved Constructs for threading c++
More information