Carnegie Mellon Concurrency and Synchronization

Size: px
Start display at page:

Download "Carnegie Mellon Concurrency and Synchronization"

Transcription

1 Concurrency and Synchronization CMPSCI 3: Computer Systems Principles

2 int pthread_join (pthread_t thread, void **value_ptr) { int result; ptw3_thread_t * tp = (ptw3_thread_t *) thread.p; if (NULL == tp thread.x!= tp>pthandle.x){ result = ESRCH; else if (PTHREAD_CREATE_DETACHED == tp>detachstate){ result = EINVAL; else { result = ; if (result == ) { result = pthreadcancelablewait (tp>threadh); *value_ptr = tp>exitstatus; result = pthread_detach (thread); return (result);

3 Typical way a function return two values int pthread_join (pthread_t thread, void **value_ptr) { int result; ptw3_thread_t * tp = (ptw3_thread_t *) thread.p; if (NULL == tp thread.x!= tp>pthandle.x){ result = ESRCH; else if (PTHREAD_CREATE_DETACHED == tp>detachstate){ result = EINVAL; else { result = ; if (result == ) { result = pthreadcancelablewait (tp>threadh); *value_ptr = tp>exitstatus; result = pthread_detach (thread); return (result); 3

4 Typical way a function return two values int pthread_join (pthread_t thread, void **value_ptr) { int result; ptw3_thread_t * tp = (ptw3_thread_t *) thread.p; if (NULL == tp thread.x!= tp>pthandle.x){ result = ESRCH; else if (PTHREAD_CREATE_DETACHED == tp>detachstate){ result = EINVAL; you need to use else { double pointer. result = ; if (result == ) { result = pthreadcancelablewait (tp>threadh); *value_ptr = tp>exitstatus; result = pthread_detach (thread); return (result); To change a pointer even outside of a function, 4

5 Concurrency and Synchronization CMPSCI 3: Computer Systems Principles 5

6 Today Sharing Mutual exclusion Semaphores 6

7 Shared Variables in Threaded C Programs Which variables in a threaded C program are shared? The answer is not as simple as global variables are shared and stack variables are private Def: A variable xis shared if and only if multiple threads reference some instance of x Requires answers to the following questions: What is the memory model for threads? How are instances of variables mapped to memory? How many threads might reference each of these instances? 7

8 Threads Memory Model Conceptual model: Multiple threads run within the context of a single process Each thread has its own separate thread context Thread ID, stack, stack pointer, PC, condition codes, and GP registers All threads share the remaining process context Code, data, heap, and shared library segments of the process virtual address space Open files and installed handlers 8

9 Threads Memory Model Conceptual model: Multiple threads run within the context of a single process Each thread has its own separate thread context Thread ID, stack, stack pointer, PC, condition codes, and GP registers All threads share the remaining process context Code, data, heap, and shared library segments of the process virtual address space Open files and installed handlers 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 The mismatch between the conceptual and operation model is a source of confusion and errors 9

10 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null);

11 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null); /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); pthread_exit vs pthread_join: Do you need further processing in main thread?

12 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null);

13 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null); /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); static acts to extend the lifetime of a variable to the lifetime of the process 3

14 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null); 4

15 Example Program to Illustrate Sharing char **ptr; /* global */ int main() { long i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; for (i = ; i < ; i++) pthread_create(&tid, NULL, thread, (void *)(i)); pthread_exit(null); /* thread routine */ void *thread(void *vargp) { long myid = (long)(vargp); static int cnt = ; printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); Peer threads reference main thread s stack indirectly through global ptr variable 5

16 Mapping Variable Instances to Memory Global variables Def: Variable declared outside of a function Virtual memory contains exactly one instance of any global variable Local variables Def: Variable declared inside function without static attribute Each thread stack contains one instance of each local variable Local static variables Def: Variable declared inside function with the static attribute Virtual memory contains exactly one instance of any local static variable. 6

17 Mapping Variable Instances to Memory Global var: instance (ptr [data]) char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); 7

18 Mapping Variable Instances to Memory Local vars: instance (i.m, msgs.m) char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); 8

19 Mapping Variable Instances to Memory char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; Local var: instances ( myid.p [peer thread s stack], myid.p [peer thread s stack] ) /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); 9

20 Mapping Variable Instances to Memory char **ptr; /* global */ int main() { int i; pthread_t tid; What if declare myid char *msgs[] static? = { "Hello from foo", "Hello from bar" ; ptr = msgs; Local var: instances ( myid.p [peer thread s stack], myid.p [peer thread s stack] ) /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt);

21 Mapping Variable Instances to Memory char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); Local static var: instance (cnt [data])

22 Mapping Variable Instances to Memory Global var: instance (ptr [data]) char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[] = { "Hello from foo", "Hello from bar" ; ptr = msgs; Local vars: instance (i.m, msgs.m) Local var: instances ( myid.p [peer thread s stack], myid.p [peer thread s stack] ) /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = ; for (i = ; i < ; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); sharing.c printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++cnt); Local static var: instance (cnt [data])

23 Shared Variable Analysis Which variables are shared? Variable Referenced by Referenced by Referenced by instance main thread? peer thread? peer thread? ptr cnt i.m msgs.m myid.p myid.p yes yes yes no yes yes yes no no yes yes yes no yes no no no yes A variable xis shared iffmultiple threads reference at least one instance of x. Thus: ptr, cnt, and msgsare shared iand myidare notshared 3

24 Synchronizing Threads Shared variables are handy... but introduce the possibility of nasty synchronization errors. 4

25 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 5

26 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); This guarantees the read/write actually happens for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 6

27 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 7

28 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); int main (int argc, char *argv argv[]) { pthread_t tid; for(int i=; i<; i++) { pthread_create(& (&tid tid, NULL, thread, &i); pthread_exit(null); return ; race.c Race /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 8

29 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c int main (int argc, char *argv argv[]) { pthread_t tid; for(int i=; i<; i++) { pthread_create(& (&tid tid, NULL, thread, &i); pthread_exit(null); return ; race.c Race No Race 9

30 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 3

31 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 3

32 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c 3

33 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; linux>./badcnt OK cnt= linux>./badcnt BOOM! cnt=336 cntshouldequal,,. What went wrong? 33

34 Assembly Code for Counter Loop C code for counter loop in thread i for (i = ; i < niters; i++) cnt++; Asm code for thread i movq (%rdi), %rcx testq %rcx,%rcx jle.l movl $, %eax.l3: movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) addq $, %rax cmpq %rcx, %rax jne.l3.l: 34

35 Assembly Code for Counter Loop C code for counter loop in thread i for (i = ; i < niters; i++) cnt++; Asm code for thread i movq (%rdi), %rcx testq %rcx,%rcx jle.l movl $, %eax.l3: movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) addq $, %rax cmpq %rcx, %rax jne.l3.l: 35

36 Assembly Code for Counter Loop C code for counter loop in thread i for (i = ; i < niters; i++) cnt++; Asm code for thread i movq (%rdi), %rcx testq %rcx,%rcx jle.l movl $, %eax.l3: movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) addq $, %rax cmpq %rcx, %rax jne.l3.l: H i : Head 36

37 Assembly Code for Counter Loop C code for counter loop in thread i for (i = ; i < niters; i++) cnt++; Asm code for thread i movq (%rdi), %rcx testq %rcx,%rcx jle.l movl $, %eax.l3: movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) addq $, %rax cmpq %rcx, %rax jne.l3.l: H i : Head L i : Load cnt U i : Update cnt S i : Store cnt 37

38 Assembly Code for Counter Loop C code for counter loop in thread i for (i = ; i < niters; i++) cnt++; Asm code for thread i movq (%rdi), %rcx testq %rcx,%rcx jle.l movl $, %eax.l3: movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) addq $, %rax cmpq %rcx, %rax jne.l3.l: H i : Head L i : Load cnt U i : Update cnt S i : Store cnt T i : Tail 38

39 iclickerquestion Suppose that cntstarts with value, and that two threads each execute the code below once. What are the possible values for cnt afterward? A) Only B) or C) or or D) None of the above movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) 39

40 iclickerquestion solution Suppose that cntstarts with value, and that two threads each execute the code below once. What are the possible values for cnt afterward? A) Only B) or C) or or D) None of the above movq cnt(%rip),%rdx addq $, %rdx movq %rdx, cnt(%rip) 4

41 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! 4

42 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i %rdx %rdx cnt 4

43 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i %rdx %rdx cnt H 43

44 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L %rdx %rdx cnt 44

45 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U %rdx %rdx cnt 45

46 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S %rdx %rdx cnt 46

47 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H %rdx %rdx cnt 47

48 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H L %rdx %rdx cnt 48

49 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H L U %rdx %rdx cnt 49

50 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H L U S %rdx %rdx cnt 5

51 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H L U S T %rdx %rdx cnt 5

52 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i H L U S H L U S T T %rdx %rdx cnt 5

53 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i %rdx %rdx cnt H L U S H L U S T T OK 53

54 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i %rdx %rdx cnt H L U S H L U S T T OK Thread critical section Thread critical section 54

55 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i %rdx %rdx cnt 55

56 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i %rdx %rdx cnt H 56

57 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L %rdx %rdx cnt 57

58 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U %rdx %rdx cnt 58

59 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H %rdx %rdx cnt 59

60 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H L %rdx %rdx cnt 6

61 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H L S %rdx %rdx cnt 6

62 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H L S T %rdx %rdx cnt 6

63 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H L S T U %rdx %rdx cnt 63

64 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i H L U H L S T U S %rdx %rdx cnt 64

65 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i %rdx %rdx cnt H L U H L S T U S T Oops! 65

66 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i %rdx %rdx cnt H L U H L S T U S T Oops! Thread critical section Thread critical section 66

67 Concurrent Execution Key idea: In general, any sequentially consistent interleaving is possible, but some give an unexpected result! I i denotes that thread iexecutes instruction I %rdx i is the content of %rdxin thread i s context i(thread) instr i %rdx %rdx cnt H L U S H L U S T T OK Thread critical section Thread critical section 67

68 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is instead of i(thread) instr i %rdx %rdx cnt H L U H L S T U S T Oops! Thread critical section Thread critical section 68

69 Concurrent Execution (cont) How about this ordering? i(thread) instr i H L H L U S U S T T %rdx %rdx cnt Oops! 69

70 Concurrent Execution (cont) How about this ordering? i(thread) instr i H L H L U S U S T T %rdx %rdx cnt Oops! We can analyze the behavior using a progress graph 7

71 Progress Graphs Thread T A progress graph depicts the discrete execution state space of concurrent threads. S U L H H L U S T Thread 7

72 Progress Graphs Thread T S A progress graph depicts the discrete execution state space of concurrent threads. Each axis corresponds to the sequential order of instructions in a thread. U L H H L U S T Thread 7

73 Progress Graphs Thread T S A progress graph depicts the discrete execution state space of concurrent threads. Each axis corresponds to the sequential order of instructions in a thread. U L H H L U S T Thread 73

74 Progress Graphs Thread T S U L A progress graph depicts the discrete execution state space of concurrent threads. Each axis corresponds to the sequential order of instructions in a thread. Each point corresponds to a possible execution state (Inst, Inst ). H H L U S T Thread 74

75 Progress Graphs Thread T S U L (L, S ) A progress graph depicts the discrete execution state space of concurrent threads. Each axis corresponds to the sequential order of instructions in a thread. Each point corresponds to a possible execution state (Inst, Inst ). H H L U S T Thread E.g., (L, S ) denotes state where thread has completed L and thread has completed S. 75

76 Trajectories in Progress Graphs Thread T S U A trajectoryis a sequenceof legal state transitionsthat describes one possibleconcurrent execution of the threads. Example: H, L, U, H, L, S, T, U, S, T L H H L U S T Thread 76

77 Critical Sections and Unsafe Regions critical section wrt cnt Thread T S U L, U, and S form acritical section with respect to the shared variable cnt Instructions in critical sections (wrtsome shared variable) shouldnot be interleaved L H H L U S T Thread critical section wrt cnt 77

78 Critical Sections and Unsafe Regions critical section wrt cnt Thread T S U L Unsafe region L, U, and S form acritical section with respect to the shared variable cnt Instructions in critical sections (wrtsome shared variable) shouldnot be interleaved Sets of states where such interleaving occurs form unsafe regions H H L U S T Thread critical section wrt cnt 78

79 Critical Sections and Unsafe Regions Thread safe T Def:A trajectory is safe iffit does not enter any unsafe region critical section wrt cnt S U Unsafe region Claim: A trajectory is correct (wrt cnt) iffit is safe L H H L U S T Thread critical section wrt cnt 79

80 Critical Sections and Unsafe Regions Thread safe T Def:A trajectory is safe iffit does not enter any unsafe region critical section wrt cnt S U L Unsafe region unsafe Claim: A trajectory is correct (wrt cnt) iffit is safe H H L U S T Thread critical section wrt cnt 8

81 iclicker question Thread T Using the program graph, classify the following trajectories as either safe or unsafe. ) H L U S H L U S T T ) H L H L U S T U S T 3) H H L U S L U S T T critical section wrt cnt S U Unsafe region A. ) Safe ) Safe 3) Safe B. ) Unsafe ) Unsafe 3) Unsafe C. ) Safe ) Unsafe 3) Safe D. ) Safe ) Unsafe 3) Unsafe L H H L U S T Thread critical section wrt cnt 8

82 iclicker question solution Thread T Using the program graph, classify the following trajectories as either safe or unsafe. ) H L U S H L U S T T ) H L H L U S T U S T 3) H H L U S L U S T T critical section wrt cnt S U Unsafe region A. ) Safe ) Safe 3) Safe B. ) Unsafe ) Unsafe 3) Unsafe C. ) Safe ) Unsafe 3) Safe D. ) Safe ) Unsafe 3) Unsafe L H H L U S T Thread critical section wrt cnt 8

83 Enforcing Mutual Exclusion Question: How can we guarantee a safe trajectory? Answer: We must synchronizetheexecution of the threads so that they can never have an unsafe trajectory. i.e., need to guarantee mutually exclusive access for each critical section. 83

84 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n", n", cnt); else printf("ok cnt=%ld\n", n", cnt); exit(); badcnt.c /* Thread routine */ void *thread(void *vargp vargp) { long i, niters = *((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; linux>./badcnt OK cnt= linux>./badcnt BOOM! cnt=336 cntshouldequal,,. What went wrong? 84

85 Enforcing Mutual Exclusion Question: How can we guarantee a safe trajectory? Answer: We must synchronizetheexecution of the threads so that they can never have an unsafe trajectory. i.e., need to guarantee mutually exclusive access for each critical section. Classic solution: Semaphores (Edsger Dijkstra) Other approaches (out of our scope) Mutex and condition variables (Pthreads) Monitors (Java) 85

86 Semaphores Semaphore: nonnegative global integer synchronization variable. 86

87 Semaphores Semaphore: nonnegative global integer synchronization variable. semaphore 87

88 Semaphores Semaphore: nonnegative global integer synchronization variable. semaphore 88

89 Semaphores Semaphore: nonnegative global integer synchronization variable. semaphore 89

90 Semaphores Semaphore: nonnegative global integer synchronization variable semaphore 9

91 Semaphores Semaphore: nonnegative global integer synchronization variable. semaphore 9

92 Semaphores Semaphore: nonnegative global integer synchronization variable. 9

93 Semaphores Semaphore: nonnegative global integer synchronization variable. 93

94 Semaphores Semaphore: nonnegative global integer synchronization variable. Manipulated by Pand Voperations. P(s) If sis nonzero, then decrement sby and return immediately. Test and decrement operations occur atomically (indivisibly) If sis zero, then suspend thread until sbecomes nonzero and the thread is restarted by a V operation. After restarting, the P operation decrements sand returns control to the caller. V(s): Increment sby. Increment operation occurs atomically If there are any threads blocked in a P operation waiting for sto become nonzero, then restart exactly one of those threads, which then completes its P operation by decrementing s. 94

95 Semaphores Semaphore: nonnegative global integer synchronization variable. Manipulated by Pand Voperations. P(s) If sis nonzero, then decrement sby and return immediately. Test and decrement operations occur atomically (indivisibly) If sis zero, then suspend thread until sbecomes nonzero and the thread is restarted by a V operation. After restarting, the P operation decrements sand returns control to the caller. V(s): Increment sby. Increment operation occurs atomically If there are any threads blocked in a P operation waiting for sto become nonzero, then restart exactly one of those threads, which then completes its P operation by decrementing s. Semaphore invariant: (s >= ) 95

96 C Semaphore Operations Pthreads functions: #include <semaphore.h> int sem_init(sem_t *s,, unsigned int val); /* s = val */ int sem_wait(sem_t *s); /* P(s) */ int sem_post(sem_t *s); /* V(s) */ 96

97 badcnt.c: Improper Synchronization /* Global shared variable */ volatile long cnt = ; /* Counter */ int main(int int argc, char **argv argv) { long niters; pthread_t tid, tid; niters = atoi(argv[]); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_create(&tid, NULL, thread, &niters niters); Pthread_join(tid, NULL); Pthread_join(tid, NULL); /* Thread routine */ void *thread thread(void *vargp vargp) { long i, niters = *(( ((long *)vargp vargp); for (i = ; i < niters; i++ ++) cnt++; return NULL; /* Check result */ if (cnt!= ( * niters)) printf("boom! cnt=%ld\n" n", cnt); else printf("ok cnt=%ld\n" n", cnt); exit(); badcnt.c How can we fix this using semaphores? 97

98 Using Semaphores for Mutual Exclusion Basic idea: Associate a unique semaphore mutex, initially, with each shared variable (or related set of shared variables). Surround corresponding critical sections with P(mutex)and V(mutex) operations. 98

99 Using Semaphores for Mutual Exclusion Basic idea: Associate a unique semaphore mutex, initially, with each shared variable (or related set of shared variables). Surround corresponding critical sections with P(mutex)and V(mutex) operations. Terminology: Binary semaphore: semaphore whose value is always or Mutex: binary semaphore used for mutual exclusion P operation: locking the mutex V operation: unlocking or releasing the mutex Holding a mutex: locked and not yet unlocked. Counting semaphore: used as a counter for set of available resources. 99

100 goodcnt.c:proper Synchronization Define and initialize a mutex for the shared variable cnt: volatile long cnt = ; /* Counter */ sem_t mutex; /* Semaphore that protects cnt */ sem_init em_init(&mutex,, ); /* mutex = */ Surround critical section with Pand V: for (i = ; i < niters; i++) { sem_wait(&mutex); mutex); cnt++; sem_post(&mutex); mutex); goodcnt.c linux>./goodcnt OK cnt= linux>./goodcnt OK cnt=

101 goodcnt.c:proper Synchronization Define and initialize a mutex for the shared variable cnt: volatile long cnt = ; /* Counter */ sem_t mutex; /* Semaphore that protects cnt */ sem_init em_init(&mutex,, ); /* mutex = */ Surround critical section with Pand V: for (i = ; i < niters; i++) { sem_wait(&mutex); mutex); cnt++; sem_post(&mutex); mutex); goodcnt.c linux>./goodcnt OK cnt= linux>./goodcnt OK cnt= Warning: It s orders of magnitude slower than badcnt.c.

102 Why MutexesWork Thread T V(s) S U Unsafe region Provide mutually exclusive access to shared variable by surrounding critical section with Pand Voperations on semaphore s(initially set to ) L P(s) H Thread H P(s) L U S V(s) T

103 Why MutexesWork Thread T V(s) S U Unsafe region Provide mutually exclusive access to shared variable by surrounding critical section with Pand Voperations on semaphore s(initially set to ) L P(s) H Initially s = Thread H P(s) L U S V(s) T 3

104 Why MutexesWork Thread T V(s) S U Unsafe region Provide mutually exclusive access to shared variable by surrounding critical section with Pand Voperations on semaphore s(initially set to ) L P(s) H Initially s = Thread H P(s) L U S V(s) T 4

105 Why MutexesWork Thread T V(s) S U Unsafe region Provide mutually exclusive access to shared variable by surrounding critical section with Pand Voperations on semaphore s(initially set to ) L P(s) Impossible H Initially s = Thread H P(s) L U S V(s) T 5

106 Why MutexesWork Thread T V(s) S U L P(s) Forbidden region Unsafe region Impossible Provide mutually exclusive access to shared variable by surrounding critical section with Pand Voperations on semaphore s(initially set to ) Semaphore invariant creates a forbidden region that encloses unsafe region and that cannot be entered by any trajectory. H Initially s = Thread H P(s) L U S V(s) T 6

107 Summary Programmers need a clear model of how variables are shared by threads. Variables shared by multiple threads must be protected to ensure mutually exclusive access. Semaphores are a fundamental mechanism for enforcing mutual exclusion. 7

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

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

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

Today. Threads review Sharing Mutual exclusion Semaphores

Today. Threads review Sharing Mutual exclusion Semaphores SYNCHRONIZATION Today Threads review Sharing Mutual exclusion Semaphores Process: Traditional View Process = process context + code, data, and stack Process context Program context: Data registers Condition

More information

Synchronization: Advanced

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

Programming with Threads Dec 7, 2009"

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

Shared Variables in Threaded C Programs. Systemprogrammering Föreläsning 11 Programming with Threads

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

for (i = 0; i < 2; i++)

for (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?

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

Process Synchroniza/on

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

Synchronization April 29, 2008

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

Carnegie Mellon. Synchroniza+on : Introduc+on to Computer Systems Recita+on 14: November 25, Pra+k Shah (pcshah) Sec+on C

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

CS3733: Operating Systems

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

Lecture #24 Synchronization

Lecture #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 information

Concurrency on x86-64; Threads Programming Tips

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

CSC 1600: Chapter 6. Synchronizing Threads. Semaphores " Review: Multi-Threaded Processes"

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

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

Introduction to Threads

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

CS 3723 Operating Systems: Final Review

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

CS 5523: Operating Systems

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

CS Operating Systems: Threads (SGG 4)

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

CS 5523 Operating Systems: Thread and Implementation

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

Threads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr.

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

Programming with Threads

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

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001

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

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff

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

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking

More 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 2018 POSIX Mike Lam, Professor Multithreading & Pthreads MIMD

More information

Concurrent Programming

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

Example. Example. Threading Language and Support. CS528 Multithreading: Programming with Threads. The boss/worker model. Thread Programming models

Example. Example. Threading Language and Support. CS528 Multithreading: Programming with Threads. The boss/worker model. Thread Programming models Threading Language and Support CS528 Multithreading: Programming with Threads A Sahu Dept of CSE, IIT Guwahati Pthread: POSIX thread Popular, Initial and Basic one Improved Constructs for threading c++

More information

Concurrent Programming

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

Carnegie Mellon Synchronization: Advanced

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

Concurrent Programming is Hard! Concurrent Programming. Reminder: Iterative Echo Server. The human mind tends to be sequential

Concurrent Programming is Hard! Concurrent Programming. Reminder: Iterative Echo Server. The human mind tends to be sequential Concurrent Programming is Hard! Concurrent Programming 15 213 / 18 213: Introduction to Computer Systems 23 rd Lecture, April 11, 213 Instructors: Seth Copen Goldstein, Anthony Rowe, and Greg Kesden The

More 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

Computer Systems Laboratory Sungkyunkwan University

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

Concurrent Programming

Concurrent Programming CHAPTER 12 Concurrent Programming 121 Concurrent Programming with Processes 935 122 Concurrent Programming with I/O Multiplexing 939 123 Concurrent Programming with Threads 947 124 Shared Variables in

More information

Note: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer Problem.

Note: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer Problem. CSCI-375 Operating Systems Lab #5 Semaphores, Producer/Consumer Problem October 19, 2016 Note: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer

More information

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

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control Processes & Threads Concurrent Programs Process = Address space + one thread of control Concurrent program = multiple threads of control Multiple single-threaded processes Multi-threaded process 2 1 Concurrent

More information

Recitation 14: Proxy Lab Part 2

Recitation 14: Proxy Lab Part 2 Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization 2 ProxyLab ProxyLab is due in 1 week. No grace days Late days allowed (-15%) Make sure to submit

More information

Proxy: Concurrency & Caches

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

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017 Preview What are Pthreads? What is Pthreads The Thread ID The Thread Creation The thread Termination The pthread_join() function Mutex The pthread_cancel function The pthread_cleanup_push() function The

More information

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

Approaches to Concurrency

Approaches to Concurrency PROCESS AND THREADS Approaches to Concurrency Processes Hard to share resources: Easy to avoid unintended sharing High overhead in adding/removing clients Threads Easy to share resources: Perhaps too easy

More 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 Carnegie Mellon 1 Concurrent Programming 15-213: Introduction to Computer Systems 23 rd Lecture, Nov. 13, 2018 2 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time

More information

Concurrent Programming

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

Total Score is updated. The score of PA4 will be changed! Please check it. Will be changed

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

Locks and semaphores. Johan Montelius KTH

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

Lecture #23 Concurrent Programming

Lecture #23 Concurrent Programming Lecture #23 Concurrent Programming Nov. 20, 2017 18-600 Foundations of Computer Systems 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking

More information

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid. Threads Dr. Ayman Abdel-Hamid, CS4254 Spring 2006 1 CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department Virginia Tech Threads Outline Threads (Chapter

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

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives Jonathan Walpole Computer Science Portland State University 1 What does a typical thread API look

More 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

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

Concurrent Programming

Concurrent Programming Concurrent Programming 15-213 / 18-213: Introduc2on to Computer Systems 23 rd Lecture, Nov. 14, 2013 Instructors: Randy Bryant, Dave O Hallaron, and Greg Kesden 1 Concurrent Programming is Hard! The human

More information

pthreads CS449 Fall 2017

pthreads CS449 Fall 2017 pthreads CS449 Fall 2017 POSIX Portable Operating System Interface Standard interface between OS and program UNIX-derived OSes mostly follow POSIX Linux, macos, Android, etc. Windows requires separate

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

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

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

ANSI/IEEE POSIX Standard Thread management

ANSI/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 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

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

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

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

CSC 252: Computer Organization Spring 2018: Lecture 26

CSC 252: Computer Organization Spring 2018: Lecture 26 CSC 252: Computer Organization Spring 2018: Lecture 26 Instructor: Yuhao Zhu Department of Computer Science University of Rochester Action Items: Programming Assignment 4 grades out Programming Assignment

More information

CS333 Intro to Operating Systems. Jonathan Walpole

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

Recitation 14: Proxy Lab Part 2

Recitation 14: Proxy Lab Part 2 Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization PXYDRIVE Demo 2 ProxyLab Checkpoint is worth 1%, due Thursday, Nov. 29 th Final is worth 7%, due

More information

Carnegie Mellon Performance of Mul.threaded Code

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

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

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

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

CSE 160 Lecture 7. C++11 threads C++11 memory model

CSE 160 Lecture 7. C++11 threads C++11 memory model CSE 160 Lecture 7 C++11 threads C++11 memory model Today s lecture C++ threads The C++11 Memory model 2013 Scott B. Baden / CSE 160 / Winter 2013 2 C++11 Threads Via , C++ supports a threading

More information

CSE 306/506 Operating Systems Threads. YoungMin Kwon

CSE 306/506 Operating Systems Threads. YoungMin Kwon CSE 306/506 Operating Systems Threads YoungMin Kwon Processes and Threads Two characteristics of a process Resource ownership Virtual address space (program, data, stack, PCB ) Main memory, I/O devices,

More information

15-213/18-213, Fall 2012 Final Exam

15-213/18-213, Fall 2012 Final Exam Andrew ID (print clearly!): Full Name: 15-213/18-213, Fall 2012 Final Exam Monday, December 10, 2012 Instructions: Make sure that your exam is not missing any sheets, then write your Andrew ID and full

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5 CS 153 Lab4 and 5 Kishore Kumar Pusukuri Outline Introduction A thread is a straightforward concept : a single sequential flow of control. In traditional operating systems, each process has an address

More information

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) pthreads 1 Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 2 1 Thread Packages Kernel thread packages Implemented and supported at kernel

More information

Lecture 5 Threads and Pthreads II

Lecture 5 Threads and Pthreads II CSCI-GA.3033-017 Special Topics: Multicore Programming Lecture 5 Threads and Pthreads II Christopher Mitchell, Ph.D. cmitchell@cs.nyu.edu http://z80.me Context We re exploring the layers of an application

More information

CS 3723 Operating Systems: Midterm II - Review

CS 3723 Operating Systems: Midterm II - Review CS 3723 Operating Systems: Midterm II - Review Instructor: Dr Tongping Liu Memory Management: Outline Background Swapping Contiguous Memory Allocation and Fragmentation Paging Structure of the Page Table

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

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

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Pthreads. 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 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

High Performance Computing Course Notes Shared Memory Parallel Programming

High Performance Computing Course Notes Shared Memory Parallel Programming High Performance Computing Course Notes 2009-2010 2010 Shared Memory Parallel Programming Techniques Multiprocessing User space multithreading Operating system-supported (or kernel) multithreading Distributed

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

Concurrent Programming

Concurrent Programming Concurrent Programming 15-213: Introduc0on to Computer Systems 22 nd Lecture, Nov. 11, 2010 Instructors: Randy Bryant and Dave O Hallaron 1 Concurrent Programming is Hard! The human mind tends to be sequen9al

More information

Dealing with Issues for Interprocess Communication

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

More information

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

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

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole The Process Concept 2 The Process Concept Process a program in execution Program - description of how to perform an activity instructions and static

More information

ANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT

ANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT ANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT Due date: 08.05.2013 Lab Hours You re expected to implement Producer-Consumer Problem that is described below. (Any form of cheating

More information

Recitation 15: Final Exam Preparation

Recitation 15: Final Exam Preparation 15-213 Recitation 15: Final Exam Preparation 25 April 2016 Ralf Brown and the 15-213 staff 1 Agenda Reminders Final Exam Review Fall 2012 exam 2 Reminders Proxy lab is due tomorrow! NO GRACE DAYS Penalty

More information

Pthread (9A) Pthread

Pthread (9A) Pthread Pthread (9A) Pthread Copyright (c) 2012 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem? What is the Race Condition? And what is its solution? Race Condition: Where several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular

More information

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

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

More information

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1 Chapter 4 Threads Images from Silberschatz Pacific University 1 Threads Multiple lines of control inside one process What is shared? How many PCBs? Pacific University 2 Typical Usages Word Processor Web

More information