Example. Example. Threading Language and Support. CS528 Multithreading: Programming with Threads. The boss/worker model. Thread Programming models
|
|
- Reynold Beasley
- 6 years ago
- Views:
Transcription
1 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++ thread : available in c++11, c++14 Java thread : very good memory model Atomic function, Mutex Thread Pooling and higher level management OpenMP (loop based) Cilk (dynamic DAG based) A Sahu 1 Thread Programming models The boss/worker model The boss/worker model The peer model A thread pipeline pp Input (Stream) Program Boss main ( ) Workers taskx tasky Files Resources Database s taskz Disks Special Devices Example main(){ /* the boss */ do(1) { get a request; switch( request ) case X: pthread_create(...,taskx); case Y: pthread_create(...,tasky); taskx(){/* worker */ perform the task, sync if accessing shared resources tasky(){/* worker */ perform the task, sync if accessing shared resources Example Above runtime overhead of creating thread Can be solved by thread pool the boss thread creates all worker thread at program Initialization and each worker thread suspends itself immediately for a wakeup call from boss 1
2 Input (static) The peer model Program Workers taskx tasky taskz Files Disks Resources Database s Special Devices Example main(){ do(1){ thread_create(...,thread1...task1); thread_create(...,thread2...task2);... signal all workers to start wait for all workers to finish do any cleanup A thread pipeline Program Filter Threads Stage 1 Stage 2 Stage 3 Input (Stream) Resources Files Files Files Databases Disks Special Devices Databases Disks Special Devices Databases Disks Special Devices Example main() { pthread_create(...,stage1); pthread_create(...,stage2);... wait for all pipeline threads to finish do any cleanup stage1() { get next input for the program do stage 1 processing of the input pass result to next thread in pipeline Example stage2(){ get input from previous thread in pipeline do stage 2 processing of the input pass result to next thread in pipeline stagen() { get input from previous thread in pipeline do stage N processing of the input pass result to program output. A Process With Multiple Threads Thread 1 (main thread) stack 1 Thread 1 context: Data registers Condition codes SP1 PC1 0 Shared code and data shared libraries run time heap read/write data read only code/data Kernel context: VM structures Descriptor table brk pointer Thread 2 (peer thread) stack 2 Thread 2 context: Data registers Condition codes SP2 PC2 2
3 Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared variables? Answer not as simple as global variables are shared and stack variables are private Requires answers to the following questions: What is the memory model for threads? How are variables mapped to memory instances? How many threads reference each of these instances? Threads Memory Model Conceptual model: Each thread runs in the context of a process Each thread has its own separate thread context Thread ID, stack, stack pointer, program counter, condition o codes, and dgeneral e purpose pose registers e s All threads share remaining process context Code, data, heap, and shared library segments of process virtual address space Open files and installed handlers Threads Memory Model Operationally, this model is not strictly enforced: Register values are truly separate and protected But any thread can read and write the stack of any other thread Mismatch between conceptual and operational model is a source of confusion and errors Threads Accessing other Thrd s Stack char **ptr; /* global */ int main(){ int i; pthread_t tid; char *msgs[n] = { "Hello1, "Hello2 ; ptr = msgs; for (i = 0; i < 2; i++) pthread_create(&tid,null,thread,(void )i); pthread_exit(null); void *thread(void *vargp) { int myid = (int)vargp; printf("[%d]: %s \n", myid, ptr[myid]); Peer threads access main thread s stack indirectly through global ptr variable Shared Variable Analysis Variable Ref by Ref by Ref by instance Whvariables main are thread? shared? peer thread 0? peer thread 1? ptr yes yes yes i.m yes no no msgs.m yes yes yes myid.p0 no yes no myid.p1 no no yes Answer: A variable x is shared iff multiple threads reference at least one instance of x. Thus: ptr and msgs are shared. i and myid are NOT shared. Parallel Counter: without Lock int cnt = 0; /* shared */ int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, count, NULL); pthread_create(&tid2, NULL, count, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); if(cnt!=niters*2)! printf("boom! cnt=%d,cnt); else printf("ok cnt=%d\n, cnt); void *count(void *arg) { for(int i=0;i<niters;i++) cnt++; cnt should be 200 What went wrong?! $./badcnt BOOM! cnt=196 $./badcnt BOOM! cnt=184 3
4 Parallel Counter: with Lock pthread_mutex M; int cnt = 0; /* shared */ int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, count, NULL); pthread_create(&tid2, NULL, count, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); if(cnt!=niters*2) printf("boom! cnt=%d,cnt); else printf("ok cnt=%d\n, cnt); void *count(void *arg) { for(int i=0;i<niters;i++) { $./goodcnt pthread_mutex_lock(&m); cnt=200 cnt++; $./goodcnt pthread_mutex_unlock(&m); cnt=200 Thread Safe and Reentrant Thread safe function (Use Mutex) Can be called simultaneously from multiple threads Even when the invocations use shared data Because all references to the shared data are serialized Reentrant function Can also be called simultaneously from multiple threads But only if each invocation uses its own data. 20 Thread Safety Functions called from a thread must be threadsafe We identify four (non disjoint) classes of thread unsafe functions: Class 1: Failing to protect shared variables Class 2: Relying on persistent state across invocations Class 3: Returning pointer to static variable Class 4: Calling thread unsafe functions Thread Unsafe Functions Class 1: Failing to protect shared variables Fix: Use Lock and unlock semaphore operations Issue: Synchronization operations will slow down code Example: goodcnt.c Thread Unsafe Functions (cont) Class 2: Relying on persistent state across multiple function invocations Random number generator relies on static state Fix: Rewrite function so that caller passes in all necessary state, Maintain Thread Specific State int rand() { static unsigned int next = 1; next = next* ; return (unsigned int)(next/65536)% 32768; void srand(unsigned int seed) { next = seed; Thread Unsafe Functions (cont) Class 3: Returning pointer to static variable Fixes: 1. Rewrite code so caller passes pointer to struct,issue: Requires changes in caller and callee Lock and copy : Issue: Requires only simple changes in caller (and none in callee), However, caller must free memory struct hostent *gethostbyname(char* name){ static struct hostent h; <contact DNS and fill in h> return &h; 4
5 Thread Unsafe Functions (cont) Class 3: Returning pointer to static variable struct hostent *gethostbyname_ts(char *p) { struct hostent *q = malloc(...); pthread_mutex_lock(&mutex); /* lock */ p = gethostbyname(name); *q = *p; /* copy */ pthread_mutex_unlock(&mutex); return q; Thread Unsafe Functions Class 4: Calling thread unsafe functions Calling one thread unsafe function makes an entire function thread unsafe Fix: Modify thefunction soit calls only thread safe functions hostp = malloc(...)); gethostbyname_r(name, hostp); Reentrant Functions A function is reentrant iff it accesses NO shared variables when called from multiple threads Reentrant functions are a proper subset of the set of threadsafe functions NOTE: The fixes to Class 2 and 3 thread unsafe functions require modifying the function to make it reentrant (only first fix for Class 3 is reentrant) All functions Thread safe functions Reentrantt functions Thread unsafe functions Thread Safe Library Functions Most functions in the Standard C Library (at the back of your K&R text) are thread safe Examples: malloc, free, printf, scanf All Unix system calls are thread safe Library calls that aren t thread safe: Thread unsafe function Class Reentrant version asctime 3 asctime_r ctime 3 ctime_r Gethostbyaddr 3 gethostbyaddr_r Gethostbyname 3 gethostbyname_r inet_ntoa 3 (none) localtime 3 localtime_r rand 2 rand_r. Many threads trying to acquire Mutex LOCK spin lock CS critical section Resets lock upon exit Synchronization Primitives int pthread_mutex_init( pthread_mutex_t *mutex_lock, const pthread_mutexattr_t *lock_attr); int pthread_mutex_lock( pthread_mutex_t *mutex_lock); int pthread_mutex_unlock( pthread_mutex_t *mutex_lock); int pthread_mutex_trylock( pthread_mutex_t *mutex_lock); 5
6 Locking Overhead Serialization points Minimize the size of critical sections Be careful Rather than wait, check if lock is available pthread _ mutex_ trylock If already locked, will return EBUSY Will require restructuring of code Suspend self by pthread_yeild() Give chance to others Suspend self by doing a timed wait.. {1, 1, 1,.., {1, 2, 3, 4,.., {1,2,4,8,.., Performance of Locking Spinning/busy wait waste time Recall MAC Protocol Non Persistence CSMA protocol Wait random time if medium if busy, then send Spin lock with exponential back off reduces contention Wait k amount of time for 1 st attempt Wait k*c i amount of time for i th attempt time Spin/Continuous Lock threads Backoff lock A Sahu slide 32 Example: simple backup void ExpBackup(int _ival){ int i=0,ival=_ival; while (i<100) { if (m.try_lock()) { ival=_ival; BigNonSharedWork();i++;m.unlock(); else { ival=ival*2; chrono::milliseconds interval(ival); this_thread::sleep_for(interval); //End Else //End while //EndExpBackup Example :simple backup int main(int argc, char *argv[]){ thread th[10]; for(int i=0;i<10;i++) th[i]=thread(expbackup, atoi(argv[1])); for(int i=0;i<10;i++) th[i].join(); return 0; Condition Variables for Synchronization Condition variable allows a thread To block itself until specified data reaches a predefined state. Condition variable Associated with a predicate (P) When the predicate becomes true, the condition variable is used to signal one or more threads waiting on the condition. Single condition variable May be associated with more than one predicate Ex: P= X OR Y AND (Z OR K) Condition Variables for Synchronization A condition variable always has a mutex associated with it. A thread locks this mutex and tests the predicate defined on the shared variable. If the predicate is not true The thread waits on the condition variable associated with the predicate Using the function pthread_cond_wait. 6
7 Condition Variables for Synchronization Pthreads provides the following functions for condition variables int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_signal(pthread_cond_t*cond); _ //Take out top thread of queue, signal that thread int pthread_cond_broadcast(pthread_cond_t *cond); int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); int pthread_cond_destroy(pthread_cond_t *cond); Barriers Synchronization Barrier holds a thread until all threads participating in the barrier have reached it Barriers can be implemented Using a counter, a mutex and a condition variable. Counter is used to keep track of the number of threads that have reached the barrier. If the count is less than the total number of threads, the threads execute a condition wait. The last thread entering (and setting the count to the number of threads) wakes up all the threads using a condition broadcast. DoWork(){ Do Phase I work Barrier(); Do Phase II work Barrier(); Do Phase III work() Barrier(); for (i=0;i<numproc;i++){ P[i].Start(DoWork); Print result(); Initialize Phase I N Phase II N 1 Phase III 2 3 N Print Result A Sahu slide 40 w1 w4 w3 w4 Example: suppose control will not pass the point before all the thread/child finishes Work barrier: phase wise work pthread_barrier typedef struct{ pthread_mutex_t pthread_cond_t int count; mylib_barrier_t; count_lock; ok_to_proceed; void mylib_init_barrier(mylib_barrier_t *b){ b > count = 0; pthread_mutex_init(&(b >count_lock), NULL); pthread_cond_init(&(b > ok_to_proceed), NULL); 41 7
8 void mylib_barrier (mylib_barrier_t *b, int num_threads) { pthread_mutex_lock(&(b > count_lock)); b > count ++; if (b > count == num_threads) { b > count = 0; pthread_cond_broadcast(&(b > ok_to_proceed)); else while (pthread_cond_wait(&(b > ok_to_proceed), &(b > count_lock))!= 0); pthread_mutex_unlock(&(b > count_lock)); Sum of all finished processor Lock P1 P2 P3 PN Every one accessing to same lock O(n) Lock1 P1 P1 PM Lock Lock2 P1 P1 PM O(lg n) Lock contention is distributed in a Tree Fashion A Sahu slide 44 Synch. Primitives pthread_mutex_init, lock, unlock, trylock pthread_attr_setdetachstate, guardsize_np, stacksize, inheritsched, schedpolicy, schedparam pthread_cond_wait, signal, broadcast, init, destroy Our main concern Lock, unlock, trylock, condsignal, condbroadcast Synchronization Hardware Many systems provide hardware support for Sync. All solutions below based on idea of locking Protecting critical regions via locks Uniprocessors could disable interrupts Currently running code would execute without preemption Generally too inefficient on multiprocessor systems Operating systems using this not broadly scalable Atomic Sync Instructions Multiprocessor disable interrupts Generally too inefficient on multiprocessor systems Operating systems using this not broadly scalable Modern machines provide special atomic hardware instructions Atomic = non interruptible Either test memory word and set value Or swap contents of two memory words Test and Set (TAS) Compare and Swap (CAS) Exchange (XCHG) Fetch and Increment (FAI) How to provide these Load Locked and Store Conditional 8
9 test_and_set Instruction : TAS //Definition: bool test_and_set(bool *target){ bool rv = *target; *target = TRUE; return rv: Executed atomically Returns the original value of passed parameter Set the new value of passed parameter to TRUE. Shared Boolean variable lock, initialized to FALSE Solution: do { while (test _ and_ set(&lock)) ; /* do nothing */ /* critical section */ lock = false; /* remainder section */ while (true); int CAS(int *value, int expected, int new_value){ int temp = *value; if (*value == expected) *value = new_value; return temp; Executed atomically Returns the original value of passed parameter value Set the variable value the value of the passed parameter new_value but only if value == expected. That is, the swap takes place only under this condition. Sync Solution using CAS Shared integer lock initialized to 0; do { while (CAS(&lock, 0, 1)!= 0) ; /* do nothing */ /* critical section */ lock = 0; /* remainder section */ while (true); Synchronization Hierarchy One == (used by )== > other LL+SC ==> TAS/CAS/FAI/XCHG==>Lock/Unlock All TAS/CAS/GAS/FAI/XCHG do the same work Lock/Unlock == > Mutex //Mutex use L/UL Mutex == > Semaphore // Semaphore uses Mutex Wait() and Signal() Semaphore == > Monitor //Monitor uses Semaphore Many wait/many Signal, Processes in Queue Monitor : Another Abstract Type which use semaphore, mutex, conditions Semaphore Semaphore: Synchronization tool Provides more sophisticated ways (than Mutex) For process to synchronize their activities. Semaphore: Abstract data type Used for controlling access, by multiple processes Can be access by two atomic Wait() and Signal() Edsger Wybe Dijkstra (SSSP Algo) Proberen (to test) Verhogen (to increment) In short P() and V() 9
10 Semaphore: Wait(), Signal() void synchronized wait(s) { while (S <= 0) ; // busy wait S ; void synchronized signal(s) { S++; synchronized function run atomically import java.util.concurrent.atomic; import java.util.concurrent.*; Binary Semaphore: Wait(), Signal() S=1; // Initialized to 1 // S =0 Locked; S=1 Available void synchronized wait(s) { while (S <= 0) ; // busy wait S ; void synchronized signal(s) { S++; A high level abstraction that provides A convenient and effective mechanism for process synchronization Monitor : Abstract data type internal variables only accessible by code within the procedure Only one process may be active within the monitor at a time Remember synchronized function of java.util Counting Semaphore: Wait(), Signal() S=50; // Initialized to 1 // S =0 Locked; S>=1 Available void synchronized wait(s) { while (S <= 0) ; // busy wait S ; void synchronized signal(s) { S++; C++ Thread Asynchronous tasks and threads Promises and tasks Mutexes and condition variables Atomics C++ Thread:atomic atomic_uint AtomicCount; void DoCount(){ int j, timesperthrd; timesperthrd=(times/num_threads); for(j=0;j<timesperthrd;j++) AtomicCount++; main(){ thread T[NUM_THREADS]; int i; for(i=0;i<num_threads;i++) T[i]=thread(DoCount); for(i=0;i<num_threads;i++) T[i].join(); 10
Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.
1 Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Last Class Review 2 ANSI/IEEE POSIX1003.1-95 Standard Thread management Work directly on threads
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 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 informationPthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Pthreads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The Pthreads API ANSI/IEEE POSIX1003.1-1995 Standard Thread management Work directly on
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: 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 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 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 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 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 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 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 informationToday. 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 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 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 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 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 information9/28/2014. CS341: Operating System. Synchronization. High Level Construct: Monitor Classical Problems of Synchronizations FAQ: Mid Semester
CS341: Operating System Lect22: 18 th Sept 2014 Dr. A. Sahu Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Synchronization Hardware Support TAS, CAS, TTAS, LL LC, XCHG, Compare, FAI
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 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 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 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 informationIntroduction to parallel computing
Introduction to parallel computing Shared Memory Programming with Pthreads (3) Zhiao Shi (modifications by Will French) Advanced Computing Center for Education & Research Vanderbilt University Last time
More informationReal Time Operating Systems and Middleware
Real Time Operating Systems and Middleware POSIX Threads Synchronization Luca Abeni abeni@dit.unitn.it Real Time Operating Systems and Middleware p. 1 Threads Synchronisation All the threads running in
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 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 informationMultithread Programming. Alexandre David
Multithread Programming Alexandre David 1.2.05 adavid@cs.aau.dk Comparison Directive based: OpenMP. Explicit parallel programming: pthreads shared memory focus on synchronization, MPI message passing focus
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 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 informationSynchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1
Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary
More informationProgramming Shared Address Space Platforms (cont.) Alexandre David B2-206
Programming Shared Address Space Platforms (cont.) Alexandre David B2-206 1 Today Finish thread synchronization. Effort for pthreads = synchronization. Effort for MPI = communication. OpenMP. Extra material
More informationCOSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References
COSC 6374 Parallel Computation Shared memory programming with POSIX Threads Fall 2012 References Some of the slides in this lecture is based on the following references: http://www.cobweb.ecn.purdue.edu/~eigenman/ece563/h
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 informationANSI/IEEE POSIX Standard Thread management
Pthread 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 The
More informationSynchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1
Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary
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 informationPOSIX Threads. HUJI Spring 2011
POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time
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 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 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 informationLecture Outline. CS 5523 Operating Systems: Concurrency and Synchronization. a = 0; b = 0; // Initial state Thread 1. Objectives.
CS 5523 Operating Systems: Concurrency and Synchronization Thank Dr. Dakai Zhu and Dr. Palden Lama for providing their slides. Lecture Outline Problems with concurrent access to shared data Ø Race condition
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 informationPosix Threads (Pthreads)
Posix Threads (Pthreads) Reference: Programming with POSIX Threads by David R. Butenhof, Addison Wesley, 1997 Threads: Introduction main: startthread( funk1 ) startthread( funk1 ) startthread( funk2 )
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 informationProcess Synchronization
Process Synchronization Part III, Modified by M.Rebaudengo - 2013 Silberschatz, Galvin and Gagne 2009 POSIX Synchronization POSIX.1b standard was adopted in 1993 Pthreads API is OS-independent It provides:
More informationHPCSE - I. «Introduction to multithreading» Panos Hadjidoukas
HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -
More informationreal time operating systems course
real time operating systems course 4 introduction to POSIX pthread programming introduction thread creation, join, end thread scheduling thread cancellation semaphores thread mutexes and condition variables
More informationThreads. Jo, Heeseung
Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU
More informationPOSIX Threads. Paolo Burgio
POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the
More informationSynchronization Primitives
Synchronization Primitives Locks Synchronization Mechanisms Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables
More informationSynchronization API of Pthread Mutex: lock, unlock, try_lock CondVar: wait, signal, signal_broadcast. Synchronization
CS341: Operating System Lect20 : 16 th Sept 2014 Dr. A. Sahu Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Synchronization API of Pthread Mutex: lock, unlock, try_lock CondVar: wait,
More information9/23/2014. Concurrent Programming. Book. Process. Exchange of data between threads/processes. Between Process. Thread.
Dr A Sahu Dept of Computer Science & Engineering IIT Guwahati Course Structure & Book Basic of thread and process Coordination and synchronization Example of Parallel Programming Shared memory : C/C++
More informationProcess Synchroniza/on
Process Synchroniza/on Andrew Case Slides adapted from Mohamed Zahran, Clark Barre9, Jinyang Li, Randy Bryant and Dave O Hallaron Topics Sharing data Race condi/ons Mutual exclusion and semaphores Sample
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 informationPOSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff
POSIX threads CS 241 February 17, 2012 Copyright University of Illinois CS 241 Staff 1 Recall: Why threads over processes? Creating a new process can be expensive Time A call into the operating system
More informationThreads need to synchronize their activities to effectively interact. This includes:
KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 8 Threads Synchronization ( Mutex & Condition Variables ) Objective: When multiple
More informationThreads. lightweight processes
Threads lightweight processes 1 Motivation Processes are expensive to create. It takes quite a bit of time to switch between processes Communication between processes must be done through an external kernel
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 informationThreads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits
CS307 What is a thread? Threads A thread is a basic unit of CPU utilization contains a thread ID, a program counter, a register set, and a stack shares with other threads belonging to the same process
More informationParallel Programming with Threads
Thread Programming with Shared Memory Parallel Programming with Threads Program is a collection of threads of control. Can be created dynamically, mid-execution, in some languages Each thread has a set
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 informationParallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai
Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai School of Computer Science and Technology Huazhong University of Science and Technology Thread Basics! All memory in the
More informationProcess Synchronization (Part I)
Process Synchronization (Part I) Amir H. Payberah amir@sics.se Amirkabir University of Technology (Tehran Polytechnic) Amir H. Payberah (Tehran Polytechnic) Process Synchronization 1393/7/14 1 / 44 Motivation
More informationConcurrency, Thread. Dongkun Shin, SKKU
Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point
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 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 informationChapter 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 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 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 informationSynchronization 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 informationSynchronization Spinlocks - Semaphores
CS 4410 Operating Systems Synchronization Spinlocks - Semaphores Summer 2013 Cornell University 1 Today How can I synchronize the execution of multiple threads of the same process? Example Race condition
More informationTHREADS. Jo, Heeseung
THREADS Jo, Heeseung TODAY'S TOPICS Why threads? Threading issues 2 PROCESSES Heavy-weight A process includes many things: - An address space (all the code and data pages) - OS resources (e.g., open files)
More informationThreads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University
Threads 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) Concurrency
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 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 informationThreads. Jo, Heeseung
Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU
More informationOperating System Labs. Yuanbin Wu
Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 4 Due: 10 Dec. Oral tests of Project 3 Date: Nov. 27 How 5min presentation 2min Q&A Operating System Labs Oral tests of Lab 3 Who
More informationRecap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack
What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for? Lightweight programming construct for concurrent activities How to implement? Kernel thread vs.
More informationA Programmer s View of Shared and Distributed Memory Architectures
A Programmer s View of Shared and Distributed Memory Architectures Overview Shared-memory Architecture: chip has some number of cores (e.g., Intel Skylake has up to 18 cores depending on the model) with
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 informationChapter 4 Concurrent Programming
Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware
More informationChapter 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 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 informationChapter 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 informationChapter 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 informationChapter 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 informationParalleland Distributed Programming. Concurrency
Paralleland Distributed Programming Concurrency Concurrency problems race condition synchronization hardware (eg matrix PCs) software (barrier, critical section, atomic operations) mutual exclusion critical
More informationProgramming Shared Address Space Platforms (Chapter 7)
Programming Shared Address Space Platforms (Chapter 7) Alexandre David 1.2.05 This is about pthreads. 1 Comparison Directive based: OpenMP. Explicit parallel programming: pthreads shared memory focus on
More informationCS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization
CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It
More informationComputer Systems Laboratory Sungkyunkwan University
Threads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Today s Topics Why threads? Threading issues 2 Processes Heavy-weight A process includes
More informationIntroduc)on to pthreads. Shared memory Parallel Programming
Introduc)on to pthreads Shared memory Parallel Programming pthreads Hello world Compute pi pthread func)ons Prac)ce Problem (OpenMP to pthreads) Sum and array Thread-safe Bounded FIFO Queue pthread Hello
More informationConcurrent Server Design Multiple- vs. Single-Thread
Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using
More informationChapter 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 informationChapter 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 informationLocks and semaphores. Johan Montelius KTH
Locks and semaphores Johan Montelius KTH 2017 1 / 41 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 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 informationLesson 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 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 informationProcesses Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.
Processes Prof. James L. Frankel Harvard University Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved. Process Model Each process consists of a sequential program
More information