Locks and semaphores. Johan Montelius KTH

Size: px
Start display at page:

Download "Locks and semaphores. Johan Montelius KTH"

Transcription

1 Locks and semaphores Johan Montelius KTH / 40

2 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++; } } int main () { pthread_t p1, p2; } pthread_ create (& p1, NULL, hello, NULL ); pthread_ create (& p2, NULL, hello, NULL ); : 2 / 40

3 Peterson s algorithm int request [2] = {0,0}; int turn = 0; int lock ( int id) { request [id] = 1; int other = 1-id; turn = other ; while ( request [ other ] == 1 && turn == other ) {}; // spin } return 1; void release ( int id) { request [id] = 0; } 3 / 40

4 Total Store Order P1 P2 4 / 40

5 Total Store Order P1 P2 a b / 40

6 Total Store Order P1 P2 a = 1 a b / 40

7 Total Store Order P1 P2 a b 0 0 a = 1 b = / 40

8 Total Store Order P1 P2 a b 0 0 a = 1 b = 1 read b read a / 40

9 Total Store Order P1 P2 a b 0 0 a = 1 b = 1 read b read a / 40

10 atomic memory operations 5 / 40

11 atomic memory operations All CPU:s provide several versions of atomic operations that both read and write to a memory element in one atomic operation. test-and-set: swap i.e. read and write to a memory location, the simplest primitive 5 / 40

12 atomic memory operations All CPU:s provide several versions of atomic operations that both read and write to a memory element in one atomic operation. test-and-set: swap i.e. read and write to a memory location, the simplest primitive fetch-and-add/and/xor/... : update the value with a given operation, more flexible 5 / 40

13 atomic memory operations All CPU:s provide several versions of atomic operations that both read and write to a memory element in one atomic operation. test-and-set: swap i.e. read and write to a memory location, the simplest primitive fetch-and-add/and/xor/... : update the value with a given operation, more flexible compare-and-swap : if the memory location contains a specific value then swap 5 / 40

14 try to lock by swap int try ( int * lock ) { return sync_val_compare_and_swap (lock, 0, 1); } 6 / 40

15 try to lock by swap int try ( int * lock ) { return sync_val_compare_and_swap (lock, 0, 1); } pushq % rbp movq %rsp, % rbp movq %rdi, -8(% rbp ) movq -8(% rbp ), % rdx movl $0, % eax movl $1, % ecx lock cmpxchgl % ecx, (% rdx ) nop popq % rbp ret 6 / 40

16 try to lock by swap int try ( int * lock ) { return sync_val_compare_and_swap (lock, 0, 1); } pushq % rbp movq %rsp, % rbp movq %rdi, -8(% rbp ) movq -8(% rbp ), % rdx movl $0, % eax movl $1, % ecx lock cmpxchgl % ecx, (% rdx ) nop popq % rbp ret This is using GCC extensions to C, similar extensions available in all compilers. 6 / 40

17 a spin-lock int lock ( int * lock ) { while ( try ( lock )!= 0) {} } return 1; 7 / 40

18 a spin-lock int lock ( int * lock ) { while ( try ( lock )!= 0) {} } return 1; void release ( int * lock ) { * lock = 0; } 7 / 40

19 finally - we re in control int global = 0; int count = 0; void * hello ( void * name ) { for ( int i = 0; i < 10; i ++) { lock (& global ); count ++; release (& global ); } } 8 / 40

20 spin locks 9 / 40

21 spin locks 9 / 40

22 avoid spinning We need to talk to the operating system. 10 / 40

23 avoid spinning We need to talk to the operating system. void lock ( int * lock ) { } while ( try ( lock )!= 0) { sched_yield (); // in Linux } 10 / 40

24 Wham -... For how long should we sleep? 11 / 40

25 Wham -... For how long should we sleep? 11 / 40

26 Wham -... For how long should we sleep? We would like to be woken up as the lock is released - before you go-go. 11 / 40

27 a detour in Sun Solaris void lock ( lock_t *m) { while ( try (m-> guard )!= 0) {}; if(m-> flag == 0) { m-> flag = 1; m-> guard = 0; } else { queue_add (m-> queue, gettid ()); m-> guard = 0; park (); } 12 / 40

28 a detour in Sun Solaris void lock ( lock_t *m) { while ( try (m-> guard )!= 0) {}; void unlock ( lock_t *m) { while ( try (m-> guard )!= 0) {}; if(m-> flag == 0) { m-> flag = 1; m-> guard = 0; } else { queue_add (m-> queue, gettid ()); m-> guard = 0; park (); } } if( empty (m-> queue )) { m-> flag = 0; } else { unpark ( dequeue (m-> queue )); } m-> guard = 0; 12 / 40

29 it s not easy It s not easy to to get it right. /* m-> flag == 1 */ : queue_add (m-> queue, gettid ()); m-> guard = 0; park (); // when I wake up the flag is set if( empty (m-> queue )) { m-> flag = 0; } else { // don t reset the flag unpark ( dequeue (m-> queue )); } 13 / 40

30 it s not easy It s not easy to to get it right. /* m-> flag == 1 */ : queue_add (m-> queue, gettid ()); setpark (); // if somone unparks now my park () is a noop m-> guard = 0; park (); if( empty (m-> queue )) { m-> flag = 0; } else { // don t reset the flag unpark ( dequeue (m-> queue )); } 13 / 40

31 back to Linux 14 / 40

32 back to Linux Introducing futex: fast user space mutex. 14 / 40

33 back to Linux Introducing futex: fast user space mutex. futex_wait(mutex, val) : suspend on the mutex if its equal to val. futex_wake(mutex) : wake one of the treads suspended on the mutex 14 / 40

34 back to Linux Introducing futex: fast user space mutex. futex_wait(mutex, val) : suspend on the mutex if its equal to val. futex_wake(mutex) : wake one of the treads suspended on the mutex In GCC you have to call them using a syscall() 14 / 40

35 a futex lock void lock ( volatile int * lock ) { while ( try ( lock )!= 0) { // time to sleep... futex_wait (lock, 1); } } 15 / 40

36 a futex lock void lock ( volatile int * lock ) { while ( try ( lock )!= 0) { // time to sleep... futex_wait (lock, 1); } } void unlock ( volatile int * lock ) { * lock = 0; futex_wake ( lock ); } 15 / 40

37 a futex lock void lock ( volatile int * lock ) { while ( try ( lock )!= 0) { // time to sleep... futex_wait (lock, 1); } } void unlock ( volatile int * lock ) { * lock = 0; futex_wake ( lock ); } Not very efficient - we want to avoid calling futex_wait() if no one is waiting. 15 / 40

38 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. 16 / 40

39 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. 16 / 40

40 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex 16 / 40

41 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... *attr) 16 / 40

42 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... pthread_mutex_destroy(pthread_mutex_t *mutex) *attr) 16 / 40

43 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... pthread_mutex_destroy(pthread_mutex_t *mutex) pthread_mutex_lock(pthread_mutex_t *mutex) *attr) 16 / 40

44 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... pthread_mutex_destroy(pthread_mutex_t *mutex) pthread_mutex_lock(pthread_mutex_t *mutex) pthread_mutex_unlock(pthread_mutex_t *mutex) *attr) 16 / 40

45 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... pthread_mutex_destroy(pthread_mutex_t *mutex) pthread_mutex_lock(pthread_mutex_t *mutex) pthread_mutex_unlock(pthread_mutex_t *mutex) *attr) 16 / 40

46 pthread mutex Using Linux futex or Sun park/unpark directly is error prone and not very portable. It s better to use the pthread library API, probably more efficient and definitely less problems. Introducing pthread mutex locks: pthread_mutex_t : structure that is the mutex pthread_mutex_init(pthread_mutex_t *mutex,... pthread_mutex_destroy(pthread_mutex_t *mutex) pthread_mutex_lock(pthread_mutex_t *mutex) pthread_mutex_unlock(pthread_mutex_t *mutex) *attr) The lock procedure is platform specific, normally implemented as a combination of spinning and yield. 16 / 40

47 What could go wrong? 17 / 40

48 What could go wrong? Nothing works, will not even compile. 17 / 40

49 What could go wrong? Nothing works, will not even compile. Deadlock: the execution is stuck, no thread is making progress. 17 / 40

50 What could go wrong? Nothing works, will not even compile. Deadlock: the execution is stuck, no thread is making progress. Livelock: we re moving around in circles, all threads think that they are doing progress but we re stuck in a loop. 17 / 40

51 What could go wrong? Nothing works, will not even compile. Deadlock: the execution is stuck, no thread is making progress. Livelock: we re moving around in circles, all threads think that they are doing progress but we re stuck in a loop. Starvation: we re making progress but some threads are stuck waiting. 17 / 40

52 What could go wrong? Nothing works, will not even compile. Deadlock: the execution is stuck, no thread is making progress. Livelock: we re moving around in circles, all threads think that they are doing progress but we re stuck in a loop. Starvation: we re making progress but some threads are stuck waiting. Unfairness: we re making progress but some threads are given more of the resources. 17 / 40

53 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

54 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

55 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

56 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

57 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

58 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: / 40

59 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: takes lock / 40

60 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: takes lock / 40

61 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: M: L: takes lock / 40

62 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: suspends on lock M: L: takes lock / 40

63 Resources, priorities and scheduling Assume we have a fixed priority scheduler, three processes with high (H), medium (M) and low (L) priority and one critical resource. H: suspends on lock M: L: takes lock / 40

64 Mars Pathfinder and Priority Inversion 19 / 40

65 Some examples concurrent counter a list a queue 20 / 40

66 the concurrent counter s t r u c t c o u n t e r _ t { i n t v a l ; } void i n c r ( s t r u c t c o u n t e r _ t c ) { c >v a l ++; } 21 / 40

67 the concurrent counter s t r u c t c o u n t e r _ t { i n t v a l ; } void i n c r ( s t r u c t c o u n t e r _ t c ) { c >v a l ++; } s t r u c t c o u n t e r _ t { i n t v a l ; pthread_mutex_t l o c k ; } void i n c r ( s t r u c t c o u n t e r _ t c ) { p t h r e a d _ l o c k ( c >l o c k ) ; c >v a l ++; p t h r e a d _ u n l o c k ( c >l o c k ) ; } 21 / 40

68 Do the right thing Doing the right thing often has a price. 22 / 40

69 Do the right thing Doing the right thing often has a price. 22 / 40

70 sloppy counter counter thread 1 23 / 40

71 sloppy counter counter thread 1 thread 2 23 / 40

72 sloppy counter counter thread 1 thread 2 thread 3 23 / 40

73 sloppy counter counter local local local thread 1 thread 2 thread 3 23 / 40

74 sloppy counter 0 counter local local local thread 1 thread 2 thread 3 23 / 40

75 sloppy counter 0 counter 1 local local local thread 1 thread 2 thread 3 23 / 40

76 sloppy counter 0 counter local local local 1 1 thread 1 thread 2 thread 3 23 / 40

77 sloppy counter 0 counter 2 local local local 1 thread 1 thread 2 thread 3 23 / 40

78 sloppy counter 0 counter local local local thread 1 thread 2 thread 3 23 / 40

79 sloppy counter 0 counter 3 local local local 1 1 thread 1 thread 2 thread 3 23 / 40

80 sloppy counter counter local local local thread 1 thread 2 thread 3 23 / 40

81 sloppy counter counter 4 local local local 2 1 thread 1 thread 2 thread 3 23 / 40

82 sloppy counter counter local local local thread 1 thread 2 thread 3 23 / 40

83 sloppy counter counter 5 local local local 2 2 thread 1 thread 2 thread 3 23 / 40

84 sloppy counter 5 counter 5 local local local 2 2 thread 1 thread 2 thread 3 23 / 40

85 sloppy counter 5 counter 0 local local local 2 2 thread 1 thread 2 thread 3 23 / 40

86 sloppy counter 5 counter 0 local local local 2 2 thread 1 thread 2 thread 3 Sloppy vs Speed - do the right thing. 23 / 40

87 how about a list Simple solution: protect the list with one lock. 24 / 40

88 how about a list Simple solution: protect the list with one lock. Concurrent solution: allow several thread to operate on the list concurrently. 24 / 40

89 how about a list Simple solution: protect the list with one lock. Concurrent solution: allow several thread to operate on the list concurrently. concurrent reading: not a problem 24 / 40

90 how about a list Simple solution: protect the list with one lock. Concurrent solution: allow several thread to operate on the list concurrently. concurrent reading: not a problem concurrent updating: / 40

91 how about a list Simple solution: protect the list with one lock. Concurrent solution: allow several thread to operate on the list concurrently. concurrent reading: not a problem concurrent updating:... hmm, how would you solve it? 24 / 40

92 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. 25 / 40

93 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy 25 / 40

94 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy 25 / 40

95 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy dummy 25 / 40

96 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy dummy 25 / 40

97 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy dummy 25 / 40

98 What about a queue Simple solution: protect the queue with one lock. Concurrent solution: allow threads to add elements to the queue at the same time as other remove elements. front end dummy 25 / 40

99 an operating system Traditionally operating systems were single threaded - the obvious solution. 26 / 40

100 an operating system Traditionally operating systems were single threaded - the obvious solution. The first systems that operated on multi-cpu architectures used one big kernel lock to avoid any problems with concurrency. 26 / 40

101 an operating system Traditionally operating systems were single threaded - the obvious solution. The first systems that operated on multi-cpu architectures used one big kernel lock to avoid any problems with concurrency. An operating system that is targeting multi-core architectures will today be multi threaded and use fine grain locking to increase performance. 26 / 40

102 an operating system Traditionally operating systems were single threaded - the obvious solution. The first systems that operated on multi-cpu architectures used one big kernel lock to avoid any problems with concurrency. An operating system that is targeting multi-core architectures will today be multi threaded and use fine grain locking to increase performance. How are things done in for example the JVM or Erlang? 26 / 40

103 beyond locks The locks that we have seen are all right: We can take a lock and prevent others from obtaining the lock. 27 / 40

104 beyond locks The locks that we have seen are all right: We can take a lock and prevent others from obtaining the lock. If someone holds the lock we will suspend execution. 27 / 40

105 beyond locks The locks that we have seen are all right: We can take a lock and prevent others from obtaining the lock. If someone holds the lock we will suspend execution. When the lock is released we will wake up and try to grab the lock again. 27 / 40

106 beyond locks The locks that we have seen are all right: We can take a lock and prevent others from obtaining the lock. If someone holds the lock we will suspend execution. When the lock is released we will wake up and try to grab the lock again. We would like to suspend and only be woken up if a specified condition holds true. 27 / 40

107 the queue revisited 28 / 40

108 the queue revisited front end dummy 28 / 40

109 the queue revisited front end dummy 28 / 40

110 the queue revisited front end dummy 28 / 40

111 the queue revisited front end dummy What do we do now? 28 / 40

112 conditional variables 29 / 40

113 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable 29 / 40

114 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) 29 / 40

115 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) 29 / 40

116 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) 29 / 40

117 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) pthread_cond_signal(pthread_cond_t *cond) 29 / 40

118 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) pthread_cond_signal(pthread_cond_t *cond) pthread_cond_broadcast(pthread_cond_t *cond) 29 / 40

119 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) pthread_cond_signal(pthread_cond_t *cond) pthread_cond_broadcast(pthread_cond_t *cond) 29 / 40

120 conditional variables Introducing pthread conditional variables: pthread_cond_t : the data structure of a conditional variable pthread_cond_init(pthread_cond_t *restrict cond,...) pthread_cond_destroy(pthread_cond_t *cond) pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) pthread_cond_signal(pthread_cond_t *cond) pthread_cond_broadcast(pthread_cond_t *cond) The exact declarations are slightly more complicated, check the man pages. 29 / 40

121 the producer/consumer A single element buffer, multiple consumers, multiple producers. int buffer ; int count = 0; 30 / 40

122 the producer/consumer A single element buffer, multiple consumers, multiple producers. int buffer ; int count = 0; void put ( int value ) { assert ( count == 0); count = 1; buffer = value ; } int get () { assert ( count == 1); count = 0; return buffer ; } 30 / 40

123 the producer/consumer A single element buffer, multiple consumers, multiple producers. int buffer ; int count = 0; void put ( int value ) { assert ( count == 0); count = 1; buffer = value ; } int get () { assert ( count == 1); count = 0; return buffer ; } Let s try to make this work. 30 / 40

124 this will not work void produce ( int val ) { put ( val ); } int consume () { int val = get (); return val ; } 31 / 40

125 add a mutex and cond variable pthread_ cond_ t cond ; pthread_ mutex_ t mutex ; 32 / 40

126 add a mutex and cond variable pthread_ cond_ t cond ; pthread_ mutex_ t mutex ; produce ( i n t v a l ) { pthread_ mutex_ lock (&mutex ) ; i f ( count == 1) pthread_cond_wait (&cond, &mutex ) ; put ( v a l ) ; p t h r e a d _ c o n d _ s i g n a l (&cond ) ; pthread_ mutex_ unlock (&mutex ) ; } 32 / 40

127 add a mutex and cond variable pthread_ cond_ t cond ; pthread_ mutex_ t mutex ; produce ( i n t v a l ) { pthread_ mutex_ lock (&mutex ) ; i f ( count == 1) pthread_cond_wait (&cond, &mutex ) ; put ( v a l ) ; p t h r e a d _ c o n d _ s i g n a l (&cond ) ; pthread_ mutex_ unlock (&mutex ) ; } i n t consume ( ) { pthread_ mutex_ lock (&mutex ) ; i f ( count == 0) pthread_cond_wait (&cond, &mutex ) ; i n t v a l = g e t ( ) ; p t h r e a d _ c o n d _ s i g n a l (&cond ) ; pthread_ mutex_ unlock (&mutex ) ; r e t u r n v a l ; } 32 / 40

128 add a mutex and cond variable pthread_ cond_ t cond ; pthread_ mutex_ t mutex ; produce ( i n t v a l ) { pthread_ mutex_ lock (&mutex ) ; i f ( count == 1) pthread_cond_wait (&cond, &mutex ) ; put ( v a l ) ; p t h r e a d _ c o n d _ s i g n a l (&cond ) ; pthread_ mutex_ unlock (&mutex ) ; } i n t consume ( ) { pthread_ mutex_ lock (&mutex ) ; i f ( count == 0) pthread_cond_wait (&cond, &mutex ) ; i n t v a l = g e t ( ) ; p t h r e a d _ c o n d _ s i g n a l (&cond ) ; pthread_ mutex_ unlock (&mutex ) ; r e t u r n v a l ; } When does this work, when does it not work? 32 / 40

129 a race condition If you re signaled to wake up - it might take some time before you do wake up. 33 / 40

130 better pthread_ cond_ t filled, empty ; pthread_ mutex_ t mutex ; 34 / 40

131 better pthread_ cond_ t filled, empty ; pthread_ mutex_ t mutex ; produce ( i n t v a l ) { pthread_ mutex_ lock (&mutex ) ; w h i l e ( count == 1) pthread_cond_wait (&empty, &mutex ) ; : p t h r e a d _ c o n d _ s i g n a l (& f i l l e d ) ; : } 34 / 40

132 better pthread_ cond_ t filled, empty ; pthread_ mutex_ t mutex ; produce ( i n t v a l ) { pthread_ mutex_ lock (&mutex ) ; w h i l e ( count == 1) pthread_cond_wait (&empty, &mutex ) ; : p t h r e a d _ c o n d _ s i g n a l (& f i l l e d ) ; : } i n t consume ( ) { pthread_ mutex_ lock (&mutex ) ; w h i l e ( count == 0) pthread_cond_wait (& f i l l e d, &mutex ) ; : p t h r e a d _ c o n d _ s i g n a l (&empty ) ; : } 34 / 40

133 a larger buffer int buffer [ MAX ]; int * getp = 0; in * putp = 0; int count = 0; void put ( int value ) { assert ( count < MAX ); buffer [ putp ] = value ; putp = putp + 1 % MAX ; count ++; } int get () { assert ( count > 0); int val = buffer [ getp ]; getp = getp + 1 % MAX count -- return val ; } 35 / 40

134 final touch produce ( int val ) { : while ( count == MAX ) pthread_cond_wait (& empty, & mutex ); : } 36 / 40

135 final touch produce ( int val ) { : while ( count == MAX ) pthread_cond_wait (& empty, & mutex ); : } int consume () { : while ( count == 0) pthread_cond_wait (& filled, & mutex ); : } 36 / 40

136 final touch produce ( int val ) { : while ( count == MAX ) pthread_cond_wait (& empty, & mutex ); : } int consume () { : while ( count == 0) pthread_cond_wait (& filled, & mutex ); : } Can we allow a producer to add an entry while another removes an entry? 36 / 40

137 Where are we now? atomic test and set: we need it 37 / 40

138 Where are we now? atomic test and set: we need it spin locks: simple to use but have some problems 37 / 40

139 Where are we now? atomic test and set: we need it spin locks: simple to use but have some problems wait and wake : avoid spinning 37 / 40

140 Where are we now? atomic test and set: we need it spin locks: simple to use but have some problems wait and wake : avoid spinning condition variables : don t wake up if it s not time to continue 37 / 40

141 Where are we now? atomic test and set: we need it spin locks: simple to use but have some problems wait and wake : avoid spinning condition variables : don t wake up if it s not time to continue Is there more? 37 / 40

142 Semaphores 38 / 40

143 Semaphores Properties of a semaphore: 38 / 40

144 Semaphores Properties of a semaphore: holds a number 38 / 40

145 Semaphores Properties of a semaphore: holds a number only allow threads to pass is number is above 0 38 / 40

146 Semaphores Properties of a semaphore: holds a number only allow threads to pass is number is above 0 passing threads decremented the number 38 / 40

147 Semaphores Properties of a semaphore: holds a number only allow threads to pass is number is above 0 passing threads decremented the number a thread can increment the number 38 / 40

148 Semaphores Properties of a semaphore: holds a number only allow threads to pass is number is above 0 passing threads decremented the number a thread can increment the number A semaphore is a counter of resources. 38 / 40

149 POSIX semaphores #include <semaphore.h> 39 / 40

150 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure 39 / 40

151 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure sem_init(sem_t *sem, int pshared, unsigned int value): could be shared between processes 39 / 40

152 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure sem_init(sem_t *sem, int pshared, unsigned int value): could be shared between processes int sem_destroy(sem_t *sem) 39 / 40

153 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure sem_init(sem_t *sem, int pshared, unsigned int value): could be shared between processes int sem_destroy(sem_t *sem) sem_wait(sem_t *sem) 39 / 40

154 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure sem_init(sem_t *sem, int pshared, unsigned int value): could be shared between processes int sem_destroy(sem_t *sem) sem_wait(sem_t *sem) sem_post(sem_t *sem) 39 / 40

155 POSIX semaphores #include <semaphore.h> sem_t : the semaphore data structure sem_init(sem_t *sem, int pshared, unsigned int value): could be shared between processes int sem_destroy(sem_t *sem) sem_wait(sem_t *sem) sem_post(sem_t *sem) 39 / 40

156 Summary

157 Summary

158 Summary

159 Summary

160 Summary

161 Summary 40 / 40

recap, 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 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 information

Locks and semaphores. Johan Montelius KTH

Locks 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 information

Multithreading Programming II

Multithreading 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 information

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Synchronization 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 information

POSIX Threads. Paolo Burgio

POSIX 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 information

real time operating systems course

real 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 information

Synchronization Mechanisms

Synchronization Mechanisms Synchronization Mechanisms CSCI 4061 Introduction to Operating Systems Instructor: Abhishek Chandra Mutex Locks Enforce protection and mutual exclusion Condition variables Allow atomic checking of conditions

More information

Operating System Labs. Yuanbin Wu

Operating 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 information

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

What 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 information

Synchronization Primitives

Synchronization 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 information

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Synchronization 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 information

Concurrency. Johan Montelius KTH

Concurrency. 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 information

Real Time Operating Systems and Middleware

Real 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 information

Synchroniza+on II COMS W4118

Synchroniza+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 information

CS 153 Lab6. Kishore Kumar Pusukuri

CS 153 Lab6. Kishore Kumar Pusukuri Outline Mutex vs Condition Variables Unlocking and locking mutex leads spinning or polling, wastes CPU time. We could sleep for some amount of time, but we do not know how long to sleep. A mutex is for

More information

Introduction to parallel computing

Introduction 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 information

Synchronization I. To do

Synchronization I. To do Synchronization I To do q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Cooperating processes Cooperating processes need

More information

Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14

Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14 Resource Access Control (2) Real-Time and Embedded Systems (M) Lecture 14 Lecture Outline Resources access control (cont d): Enhancing the priority ceiling protocol Stack-based priority ceiling protocol

More information

Synchronization I. Today. Next time. Race condition, critical regions and locks. Condition variables, semaphores and Monitors

Synchronization I. Today. Next time. Race condition, critical regions and locks. Condition variables, semaphores and Monitors Synchronization I Today Race condition, critical regions and locks Next time Condition variables, semaphores and Monitors Cooperating processes Cooperating processes need to communicate They can affect/be

More information

W4118 Operating Systems. Instructor: Junfeng Yang

W4118 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 information

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

CSci 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 information

Locks. Dongkun Shin, SKKU

Locks. Dongkun Shin, SKKU Locks 1 Locks: The Basic Idea To implement a critical section A lock variable must be declared A lock variable holds the state of the lock Available (unlocked, free) Acquired (locked, held) Exactly one

More information

CSC Systems Programming Fall Lecture - XIV Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 2nd, 2010

CSC Systems Programming Fall Lecture - XIV Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 2nd, 2010 CSC 4304 - Systems Programming Fall 2010 Lecture - XIV Concurrent Programming Tevfik Ko!ar Louisiana State University November 2nd, 2010 1 Concurrency Issues 2 Concurrency Issues 3 Synchronization Mechanism

More information

Synchronization I. Today. Next time. Monitors. ! Race condition, critical regions and locks. ! Condition variables, semaphores and

Synchronization I. Today. Next time. Monitors. ! Race condition, critical regions and locks. ! Condition variables, semaphores and Synchronization I Today! Race condition, critical regions and locks Next time! Condition variables, semaphores and Monitors Cooperating processes! Cooperating processes need to communicate They can affect/be

More information

1 Introduction. 2 total-store-order. Take me for a spin. 2.1 Peterson's algorithm. Johan Montelius HT2016

1 Introduction. 2 total-store-order. Take me for a spin. 2.1 Peterson's algorithm. Johan Montelius HT2016 Take me for a spin Johan Montelius HT2016 1 Introduction We will rst experience that we can not implement any synchronization primitives using regular read and write operations. Then we will implement

More information

Lecture 9: Thread Synchronizations. Spring 2016 Jason Tang

Lecture 9: Thread Synchronizations. Spring 2016 Jason Tang Lecture 9: Thread Synchronizations Spring 2016 Jason Tang Slides based upon Operating System Concept slides, http://codex.cs.yale.edu/avi/os-book/os9/slide-dir/index.html Copyright Silberschatz, Galvin,

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

Final Examination (Fall 2016) (Section 1)

Final Examination (Fall 2016) (Section 1) CS 453/552: Operating Systems Final Examination (Fall 2016) (Section 1) Time: 120 minutes Name : Total Points: 150 Please read the following carefully. You get five points for writing your name above!

More information

Implementing Locks. Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau)

Implementing Locks. Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Implementing Locks Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Lock Implementation Goals We evaluate lock implementations along following lines Correctness Mutual exclusion: only one

More information

Network Programming TDC 561

Network Programming TDC 561 Network Programming TDC 561 Lecture # 6: Multithreaded Servers Dr. Ehab S. Al-Shaer School of Computer Science & Telecommunication DePaul University Chicago, IL 1 Introduction to Multithreaded Network

More information

Process Synchronization. studykorner.org

Process Synchronization. studykorner.org Process Synchronization Semaphore Implementation Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time The main disadvantage of the semaphore definition

More information

Process Synchronization (Part I)

Process 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 information

Week 3. Locks & Semaphores

Week 3. Locks & Semaphores Week 3 Locks & Semaphores Synchronization Mechanisms Locks Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

More information

The course that gives CMU its Zip! Concurrency II: Synchronization Nov 14, 2000

The 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 information

Synchronising Threads

Synchronising Threads Synchronising Threads David Chisnall March 1, 2011 First Rule for Maintainable Concurrent Code No data may be both mutable and aliased Harder Problems Data is shared and mutable Access to it must be protected

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, 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 information

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017

Data 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 information

Solving the Producer Consumer Problem with PThreads

Solving the Producer Consumer Problem with PThreads Solving the Producer Consumer Problem with PThreads Michael Jantz Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads: Producer-Consumer 1 Introduction This lab is an extension of last week's lab.

More information

TCSS 422: OPERATING SYSTEMS

TCSS 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 information

Operating Systems. Thread Synchronization Primitives. Thomas Ropars.

Operating 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 information

Synchronization 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 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 information

Multithread Programming. Alexandre David

Multithread 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 information

Real Time Operating System Support for Concurrency

Real Time Operating System Support for Concurrency Real Time Operating System Support for Concurrency Colin Perkins teaching/2003-2004/rtes4/lecture13.pdf Lecture Outline Resources and Resource access control Synchronisation and Locking Implementing priority

More information

Synchronization. Disclaimer: some slides are adopted from the book authors slides with permission 1

Synchronization. Disclaimer: some slides are adopted from the book authors slides with permission 1 Synchronization Disclaimer: some slides are adopted from the book authors slides with permission 1 What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for?

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

More information

Process Synchronization(2)

Process Synchronization(2) EECS 3221.3 Operating System Fundamentals No.6 Process Synchronization(2) Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University Semaphores Problems with the software solutions.

More information

Thread. 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 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 information

Paralleland Distributed Programming. Concurrency

Paralleland 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 information

Process Synchronization(2)

Process Synchronization(2) CSE 3221.3 Operating System Fundamentals No.6 Process Synchronization(2) Prof. Hui Jiang Dept of Computer Science and Engineering York University Semaphores Problems with the software solutions. Not easy

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

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

Condition 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 information

Synchronization 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 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 information

KING 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. 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 information

CSCE 313: Introduction to Computer Systems

CSCE 313: Introduction to Computer Systems CSCE 313 Introduction to Computer Systems Instructor: Dr. Guofei Gu http://courses.cse.tamu.edu/guofei/csce313 POSIX Thread Synchronization Mutex Locks Condition Variables Read-Write Locks Semaphores Reading:

More information

Thread and Synchronization

Thread and Synchronization Thread and Synchronization pthread Programming (Module 19) Yann-Hang Lee Arizona State University yhlee@asu.edu (480) 727-7507 Summer 2014 Real-time Systems Lab, Computer Science and Engineering, ASU Pthread

More information

[537] Locks and Condition Variables. Tyler Harter

[537] Locks and Condition Variables. Tyler Harter [537] Locks and Condition Variables Tyler Harter Review: using and designing basic locks Do it. Problem 1 Lock Evaluation How to tell if a lock implementation is good? Lock Evaluation How to tell if a

More information

Process Synchronization(2)

Process Synchronization(2) EECS 3221.3 Operating System Fundamentals No.6 Process Synchronization(2) Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University Semaphores Problems with the software solutions.

More information

In class we examined the need for concurrent execution paths like a consumer and a producer to synchronize their access to a shared ring buffer.

In class we examined the need for concurrent execution paths like a consumer and a producer to synchronize their access to a shared ring buffer. In class we examined the need for concurrent execution paths like a consumer and a producer to synchronize their access to a shared ring buffer. Below are a set of global objects which are accessible to

More information

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012 Pre-lab #2 tutorial ECE 254 Operating Systems and Systems Programming May 24, 2012 Content Concurrency Concurrent Programming Thread vs. Process POSIX Threads Synchronization and Critical Sections Mutexes

More information

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005 Threads vs. Processes Lecture 4 Thread Programming January 21, 2005 fork() is expensive (time, memory) Interprocess communication is hard. Threads are lightweight processes: one process can contain several

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 3: CCR, monitors, and concurrency in practice DrRobert N. M. Watson 1 Reminder from last time Implementing mutual exclusion: hardware support for atomicity and inter-processor

More information

Condition Variables & Semaphores

Condition Variables & Semaphores Condition Variables & Semaphores Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau) Review: Concurrency Objectives Mutual Exclusion A & B don t run at the same time Solved using locks Ordering

More information

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Carnegie 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 information

Synchronization: Basics

Synchronization: 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 information

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

Recap: 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 information

Interprocess Communication and Synchronization

Interprocess Communication and Synchronization Chapter 2 (Second Part) Interprocess Communication and Synchronization Slide Credits: Jonathan Walpole Andrew Tanenbaum 1 Outline Race Conditions Mutual Exclusion and Critical Regions Mutex s Test-And-Set

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

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective?

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective? CS 470 Spring 2019 POSIX Mike Lam, Professor Multithreading & Pthreads MIMD

More information

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions CS 470 Spring 2018 Mike Lam, Professor Semaphores and Conditions Synchronization mechanisms Busy-waiting (wasteful!) Atomic instructions (e.g., LOCK prefix in x86) Pthreads Mutex: simple mutual exclusion

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

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

[537] Semaphores. Tyler Harter

[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 information

Multi-threaded Programming

Multi-threaded Programming Multi-threaded Programming Trifon Ruskov ruskov@tu-varna.acad.bg Technical University of Varna - Bulgaria 1 Threads A thread is defined as an independent stream of instructions that can be scheduled to

More information

Introduction to PThreads and Basic Synchronization

Introduction to PThreads and Basic Synchronization Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization

More information

CMSC421: Principles of Operating Systems

CMSC421: Principles of Operating Systems CMSC421: Principles of Operating Systems Nilanjan Banerjee Assistant Professor, University of Maryland Baltimore County nilanb@umbc.edu http://www.csee.umbc.edu/~nilanb/teaching/421/ Principles of Operating

More information

Today: Synchronization. Recap: Synchronization

Today: Synchronization. Recap: Synchronization Today: Synchronization Synchronization Mutual exclusion Critical sections Example: Too Much Milk Locks Synchronization primitives are required to ensure that only one thread executes in a critical section

More information

Synchronization: Basics

Synchronization: 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 information

ECE 574 Cluster Computing Lecture 8

ECE 574 Cluster Computing Lecture 8 ECE 574 Cluster Computing Lecture 8 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 16 February 2017 Announcements Too many snow days Posted a video with HW#4 Review HW#5 will

More information

Deterministic Futexes Revisited

Deterministic Futexes Revisited A. Zuepke Deterministic Futexes Revisited Alexander Zuepke, Robert Kaiser first.last@hs-rm.de A. Zuepke Futexes Futexes: underlying mechanism for thread synchronization in Linux libc provides: Mutexes

More information

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency and Synchronization ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Concurrency Multiprogramming Supported by most all current operating systems More than one unit of

More information

C09: Process Synchronization

C09: Process Synchronization CISC 7310X C09: Process Synchronization Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/29/2018 CUNY Brooklyn College 1 Outline Race condition and critical regions The bounded

More information

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

CS-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 information

Midterm I SOLUTIONS October 14 th, 2015 CS162: Operating Systems and Systems Programming

Midterm I SOLUTIONS October 14 th, 2015 CS162: Operating Systems and Systems Programming University of California, Berkeley College of Engineering Computer Science Division EECS Fall 2015 John Kubiatowicz Midterm I SOLUTIONS October 14 th, 2015 CS162: Operating Systems and Systems Programming

More information

Concurrency: a crash course

Concurrency: a crash course Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute

More information

Faculté Polytechnique

Faculté Polytechnique Faculté Polytechnique Real-Time Systems - Practical Work 5 POSIX Threads Dr Frémal Sébastien Sebastien.FREMAL@umons.ac.be Ir Michel Bagein Michel.BAGEIN@umons.ac.be Prof. Pierre Manneback Pierre.MANNEBACK@umons.ac.be

More information

CS345 Opera,ng Systems. Φροντιστήριο Άσκησης 2

CS345 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 information

CS5460: Operating Systems

CS5460: Operating Systems CS5460: Operating Systems Lecture 9: Implementing Synchronization (Chapter 6) Multiprocessor Memory Models Uniprocessor memory is simple Every load from a location retrieves the last value stored to that

More information

Process Synchronization

Process 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 information

CS 550 Operating Systems Spring Concurrency Semaphores, Condition Variables, Producer Consumer Problem

CS 550 Operating Systems Spring Concurrency Semaphores, Condition Variables, Producer Consumer Problem 1 CS 550 Operating Systems Spring 2018 Concurrency Semaphores, Condition Variables, Producer Consumer Problem Semaphore Semaphore is a fundamental synchronization primitive used for Locking around critical

More information

CSE 421/521 - Operating Systems Fall 2011 Recitations. Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar. Presented by...

CSE 421/521 - Operating Systems Fall 2011 Recitations. Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar. Presented by... CSE 421/521 - Operating Systems Fall 2011 Recitations Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar Presented by... University at Buffalo September..., 2011 1 Network Programming

More information

CSE 451 Midterm 1. Name:

CSE 451 Midterm 1. Name: CSE 451 Midterm 1 Name: 1. [2 points] Imagine that a new CPU were built that contained multiple, complete sets of registers each set contains a PC plus all the other registers available to user programs.

More information

Concurrent Server Design Multiple- vs. Single-Thread

Concurrent 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 information

Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors

Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Synchronization I q Race condition, critical regions q Locks and concurrent data structures q Next time: Condition variables, semaphores and monitors Cooperating processes and threads Cooperating processes

More information

Threads need to synchronize their activities to effectively interact. This includes:

Threads 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 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

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

Condition Variables. Dongkun Shin, SKKU

Condition Variables. Dongkun Shin, SKKU Condition Variables 1 Why Condition? cases where a thread wishes to check whether a condition is true before continuing its execution 1 void *child(void *arg) { 2 printf("child\n"); 3 // XXX how to indicate

More information

Semaphores Semaphores: A Definition

Semaphores 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 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

POSIX Semaphores. Operations on semaphores (taken from the Linux man page)

POSIX Semaphores. Operations on semaphores (taken from the Linux man page) POSIX Semaphores A variable of type sem_t Example Declaration of a semaphore sem_t sem; Operations on semaphores (taken from the Linux man page) int sem_init(sem_t *sem, int pshared, unsigned int value);

More information