Programming with Threads
|
|
- Beverly Hart
- 5 years ago
- Views:
Transcription
1 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 with semaphores Thread safety and reentrancy Races and deadlocks
2 Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared variables? 2 The answer is not as simple as global variables are shared and stack variables are private. We must understand what is shared and what is not shared. Requires answers to the following questions: What is the memory model for threads? How are instances of the variables mapped to memory? How many threads reference each of these instances? The variable is shared if and only if multiple threads reference some of instance of the variable.
3 Threads Memory Model Conceptual model: Each thread runs in the context of a process. Each thread has its own separate thread context. Thread ID, stack, stack pointer, program counter, condition codes, and general purpose registers. All threads share the remaining process context. Code, R/W data, heap, and shared library code and data areas (segments of the process virtual address space.) Open files and installed handlers 3
4 Threads Memory Model (cont) Operationally, this model is not strictly enforced: While register values are truly separate and protected... It is impossible for one thread to read or write the register values of another thread Any thread can access any location in the shared virtual memory - read and write the stack of any other thread - If one thread modifies a memory location, then every other thread will see the change, if it reads that location. Registers are never shared, virtual memory is always shared. Mismatch between the conceptual and operation model is a source of confusion and errors. 4
5 Example of Threads Accessing Another Thread s Stack #include "csapp.h" #define N 2 void *thread(void *vargp); char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[n] = { "Hello from Block - A", "Hello from Block - B" }; ptr = msgs; for (i = 0; i < 2; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); } 5 /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = 0; } printf("[%d]: %s (cnt=%d)\n", myid, ptr[myid], ++cnt); Peer threads access main thread s stack indirectly through global ptr variable
6 conc]$./sharing [0]: Hello from Block - A (cnt=1) [1]: Hello from Block - B (cnt=2) [sanjay@dslabsrv17 conc]$ Thread Stacks: Contained in the stack area of the virtual address space, and are usually accessed independently of their respective threads. Different thread stacks are not protected from other threads, i.e. if a thread can somehow manage to acquire a pointer to another thread s stack, then it can read and write any part of that stack. 6
7 Mapping Variables to Memory Variables Global Variables Any variable declared outside of a function. At run time, the read/write area of virtual memory contains exactly one instance of each global variable that can be referenced by any thread. For example, the global ptr variable has one runtime instance in the R/W area of virtual memory. When there is only one instance of a variable, we will denote the instance by simply using the variable name, e.g. ptr 7
8 Mapping Variables to Memory Variables (cont) Local automatic variables A local automatic variable is one that is declared inside a function without the static attribute. At run time, each thread s stack contains its own instances of any local automatic variables. It is true even if multiple threads execute the same thread routine. For example, There is one instance of the local variable tid, and it resides on the stack of the main thread. We will denote this instance as tid.m. There are two instances of the local variable myid, one instance on the stack of peer thread 0 and the other on the stack of peer thread 1. We will denote these instances as myid.p0 and myid.p1, respectively. 8
9 Mapping Variables to Memory Variables (cont) Local Static Variables A local static variable is one that is declared inside a function with the static attribute. As with global variables, R/W area of virtual memory contains exactly one instance of each local static variable declared in the program. For example, even though each peer thread in our program declares cnt in line 25, at run time there is only one instance of cnt residing in the R/W area of virtual memory. Each peer thread reads and writes this instance. 9
10 Shared Variables A variable v is shared if and only if one of its instances is referenced by more than one thread. For example, Variable cnt is shared because it has one run-time instance, and this instance is referenced in both peer threads. Variable myid is not shared because each of its two instances is referenced by exactly on thread. It is important to note that local automatic variables such as msgs can also be shared. 10
11 Mapping Variables to Mem. Instances Global var: 1 instance (ptr [data]) Local automatic vars: 1 instance (i.m, msgs.m ) char **ptr; /* global */ int main() { int i; pthread_t tid; char *msgs[n] = { "Hello from Block - A", "Hello from Block - B" }; ptr = msgs; for (i = 0; i < 2; i++) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); } 11 Local automatic var: 2 instances ( myid.p0[peer thread 0 s stack], myid.p1[peer thread 1 s stack] ) /* thread routine */ void *thread(void *vargp) { int myid = (int)vargp; static int cnt = 0; } printf("[%d]: %s (cnt=%d)\n", myid, ptr[myid], ++cnt); Local static var: 1 instance (cnt [data])
12 Shared Variable Analysis Which variables are shared? Variable Referenced by Referenced by Referenced by instance main thread? peer thread 0? peer thread 1? ptr yes yes yes svar no yes yes i.m yes no no msgs.m yes yes yes myid.p0 no yes no myid.p1 no no yes Answer: A variable x is shared iff multiple threads reference at least one instance of x. Thus: ptr, cnt, and msgs are shared. i and myid are NOT shared. 12
13 badcnt.c: An Improperly Synchronized Threaded Program #include "csapp.h #define NITERS void *count(void *arg); unsigned int cnt = 0; /* shared */ int main() { pthread_t tid1, tid2; Pthread_create(&tid1, NULL, count, NULL); Pthread_create(&tid2, NULL, count, NULL); Pthread_join(tid1, NULL); Pthread_join(tid2, NULL); if (cnt!= (unsigned)niters*2) printf( Value of cnt variable not proper!! cnt=%d\n, cnt); else printf("ok cnt=%d\n", cnt); 13 } /* thread routine */ void *count(void *arg) { int i; for (i=0; i<niters; i++) cnt++; return NULL; }
14 conc]$./badcnt Value of cnt variable not proper! cnt= conc]$./badcnt Value of cnt variable not proper! cnt= conc]$./badcnt Value of cnt variable not proper! cnt= conc]$ cnt should be equal to 200,000,000. What went wrong?! 14
15 Assembly Code for Counter Loop C code for counter loop for (i=0; i<niters; i++) cnt++; Head (H i ) Load cnt (L i ) Update cnt (U i ) Store cnt (S i ) Tail (T i ).L9:.L12:.L11:.L10: Corresponding asm code (gcc -O0 -fforce-mem) movl -4(%ebp),%eax cmpl $ ,%eax jle.l12 jmp.l10 movl cnt,%eax # Load leal 1(%eax),%edx # Update movl %edx,cnt # Store movl -4(%ebp),%eax leal 1(%eax),%edx movl %edx,-4(%ebp) jmp.l9 15
16 Concurrent Execution Five parts of loop code: H i : The block of instructions at the head of the loop. L i : The instruction that loads the shared variable cnt into register %eax i, where %eax, denotes the value of register %eax in thread i. U i : The instruction that updates (increments) %eax i. S i : The instruction that stores the updated value of %eax i back to the shared variable cnt. T i : the block of instructions at the tail of the loop. 16
17 Concurrent Execution (cont) Key idea: In general, any sequentially consistent interleaving is possible, but some are incorrect! I i denotes that thread i executes instruction I %eax i is the contents of %eax in thread i s context i (thread) instr i %eax 1 %eax 2 cnt H 1 L 1 U 1 S 1 H 2 L 2 U 2 S 2 T 2 T Correct Ordering
18 Concurrent Execution (cont) Incorrect ordering: two threads increment the counter, but the result is 1 instead of 2. i (thread) instr i cnt H 1 L 1 U 1 H 2 L 2 S 1 T 1 U 2 S 2 T 2 %eax 1 %eax Incorrect Ordering
19 Concurrent Execution (cont) How about this ordering? i (thread) instr i cnt %eax 1 %eax H 1 L 1 H 2 L 2 U 2 S 2 U 1 S 1 T 1 T 2 We can clarify our understanding of concurrent execution with the help of the progress graph 19
20 Progress Graphs Thread 2 T 2 S 2 U 2 L 2 (L 1, S 2 ) 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 1, Inst 2 ). H 2 H 1 L 1 U 1 S 1 T 1 Thread 1 E.g., (L 1, S 2 ) denotes state where thread 1 has completed L 1 and thread 2 has completed S 2. 20
21 Trajectories in Progress Graphs Thread 2 T 2 S 2 A trajectory is a sequence of legal state transitions that describes one possible concurrent execution of the threads. Example: U 2 L 2 H1, L1, U1, H2, L2, S1, T1, U2, S2, T2 H 2 H 1 L 1 U 1 S 1 T 1 Thread 1 21
22 Critical Sections and Unsafe Regions Thread 2 T 2 L, U, and S form a critical section with respect to the shared variable cnt. critical section wrt cnt S 2 U 2 L 2 Unsafe region Instructions in critical sections (wrt to some shared variable) should not be interleaved. Sets of states where such interleaving occurs form unsafe regions. H 2 H 1 L 1 U 1 S 1 T 1 Thread 1 critical section wrt cnt 22
23 Safe and Unsafe Trajectories Thread 2 critical section wrt cnt T 2 S 2 U 2 Safe trajectory Unsafe region Unsafe trajectory Def: A trajectory is safe iff it doesn t touch any part of an unsafe region. Claim: A trajectory is correct (wrt cnt) iff it is safe. L 2 H 2 H 1 L 1 U 1 S 1 T 1 Thread 1 critical section wrt cnt 23
24 Semaphores Question: How can we guarantee a safe trajectory? We must synchronize the threads so that they never enter an unsafe state. Classic solution: Dijkstra's P and V operations on semaphores. semaphore: non-negative integer synchronization variable. P(s): [ while (s == 0) wait(); s--; ]» Dutch for "Proberen" (test) V(s): [ s++; ]» Dutch for "Verhogen" (increment) OS guarantees that operations between brackets [ ] are executed indivisibly. Only one P or V operation at a time can modify s. When while loop in P terminates, only that P can decrement s. Semaphore invariant: (s >= 0) 24
25 Safe Sharing with Semaphores Here is how we would use P and V operations to synchronize the threads that update cnt. /* Semaphore s is initially 1 */ /* Thread routine */ void *count(void *arg) { int i; } for (i=0; i<niters; i++) { P(s); cnt++; V(s); } return NULL; 25
26 Safe Sharing With Semaphores Thread 2 T 2 V(s) S 2 U 2 L 2 P(s) Forbidden region Unsafe region Provide mutually exclusive access to shared variable by surrounding critical section with P and V operations on semaphore s (initially set to 1). Semaphore invariant creates a forbidden region that encloses unsafe region and is never touched by any trajectory. H Initially s = 1 26 H 1 P(s) L 1 U 1 S 1 V(s) T 1 Thread 1
27 POSIX Semaphores #include <semaphore.h> Note: Refer /usr/include/semaphore.h int sem_init(sem_t *sem, o, unsinged int value); int sem_wait(sem_t *s); /* P(s) */ int sem_post(sem_t *s); /* V(s) */ P and V Operations will be performed by calling the sem_wait and sem_post functions respectively. Following wrapper functions are defined: #include csapp.h void P(sem_t *s); /Wrapper function for sem_wait */ void S(sem_t *s); /Wrapper function for sem_post */ 27
28 POSIX Semaphores (cont) /* Initialize semaphore sem to value */ /* pshared=0 if thread, pshared=1 if process */ void Sem_init(sem_t *sem, int pshared, unsigned int value) { if (sem_init(sem, pshared, value) < 0) unix_error("sem_init"); } /* P operation on semaphore sem */ void P(sem_t *sem) { if (sem_wait(sem)) unix_error("p"); } /* V operation on semaphore sem */ void V(sem_t *sem) { if (sem_post(sem)) unix_error("v"); 28
29 Sharing With POSIX Semaphores /* * goodcnt.c - A properly synchronized counter program */ /* $begin goodcnt */ #include "csapp.h" #define NITERS void *count(void *arg); /* shared variables */ unsigned int cnt; /* counter */ sem_t mutex; /* semaphore that protects counter */ int main() { pthread_t tid1, tid2; Sem_init(&mutex, 0, 1); /* mutex = 1 */ Pthread_create(&tid1, NULL, count, NULL); Pthread_create(&tid2, NULL, count, NULL); Pthread_join(tid1, NULL); Pthread_join(tid2, NULL); 29 if (cnt!= (unsigned)niters*2) printf("value of cnt variable not proper!! %d\n", cnt); else printf("ok cnt=%d\n", cnt); exit(0); }
30 Sharing With POSIX Semaphores (cont) /* thread routine */ void *count(void *arg) { int i; for (i = 0; i < NITERS; i++) { P(&mutex); cnt++; V(&mutex); } return NULL; } 30
31 31 conc]$./goodcnt OK cnt= conc]$./goodcnt OK cnt= conc]$./goodcnt OK cnt=
32 Signaling With Semaphores producer thread shared buffer consumer thread Common synchronization pattern: 32 Producer waits for slot, inserts item in buffer, and signals consumer. Consumer waits for item, removes it from buffer, and signals producer. signals in this context has nothing to do with Unix signals Examples Multimedia processing: Producer creates MPEG video frames, consumer renders the frames Event-driven graphical user interfaces Producer detects mouse clicks, mouse movements, and keyboard hits and inserts corresponding events in buffer. Consumer retrieves events from buffer and paints the display.
33 Using semaphores to Schedule Shared Resources SBUF package: to build producer-consumer programs. It manipulates buffers of type sbuf_t Items are stored in a dynamically allocated integer array (buf) with n items. front and rear indices keep track of the first and last items in the array. Three semaphores control synchronize access to the buffer. mutex semaphore provides mutually exclusive buffer access. slots and items semaphores count the number of empty slots and available items respectively. 33
34 Using semaphores to Schedule Shared Resources The sbuf_init function allocates heap memory for the buffer, sets front and rear to indicate an empty buffer, and assigns initial values to the three semaphores The sbuf_deinit function frees the buffer storage when the application is completed The sbuf_insert function waits for an available slot, locks the mutex, adds the item, unlock the mutex and the announces the availability of a new item. The sbuf_remove function is symmetric. After waiting for an available buffer item, it locks the mutex, removes the item from the front of the buffer, unlocks mutex, and then signal the availability of a new slot. 34
35 Using semaphores to Schedule Shared Resources #ifndef SBUF_H #define SBUF_H #include "csapp.h /* $begin sbuft Shared Buffer */ typedef struct { int *buf; /* Buffer array */ int n; /* Maximum number of slots */ int front; /* buf[(front+1)%n] is first item */ int rear; /* buf[rear%n] is last item */ sem_t mutex; /* Protects accesses to buf */ sem_t slots; /* Counts available slots */ sem_t items; /* Counts available items */ } sbuf_t; /* $end sbuft */ void sbuf_init(sbuf_t *sp, int n); void sbuf_deinit(sbuf_t *sp); void sbuf_insert(sbuf_t *sp, int item); int sbuf_remove(sbuf_t *sp); #endif 35 /* SBUF_H */
36 /* sbuf.c $begin sbufc */ #include "csapp.h" #include "sbuf.h" /* Create an empty, bounded, shared FIFO buffer with n slots */ /* $begin sbuf_init */ void sbuf_init(sbuf_t *sp, int n) { sp->buf = Calloc(n, sizeof(int)); sp->n = n; /* Buffer holds max of n items */ sp->front = sp->rear = 0; /* Empty buffer iff front == rear */ Sem_init(&sp->mutex, 0, 1); /* Binary semaphore for locking */ Sem_init(&sp->slots, 0, n); /* Initially, buf has n empty slots */ Sem_init(&sp->items, 0, 0); /* Initially, buf has zero data items */ } /* $end sbuf_init */ /* Clean up buffer sp */ /* $begin sbuf_deinit */ void sbuf_deinit(sbuf_t *sp) { Free(sp->buf); } /* $end sbuf_deinit */ 36
37 /* Insert item onto the rear of shared buffer sp */ /* $begin sbuf_insert */ void sbuf_insert(sbuf_t *sp, int item) { P(&sp->slots); /* Wait for available slot */ P(&sp->mutex); /* Lock the buffer */ sp->buf[(++sp->rear)%(sp->n)] = item; /* Insert the item */ V(&sp->mutex); /* Unlock the buffer */ V(&sp->items); /* Announce available item */ } /* $end sbuf_insert */ /* Remove and return the first item from buffer sp */ /* $begin sbuf_remove */ int sbuf_remove(sbuf_t *sp) { int item; P(&sp->items); /* Wait for available item */ P(&sp->mutex); /* Lock the buffer */ item = sp->buf[(++sp->front)%(sp->n)]; /* Remove the item */ V(&sp->mutex); /* Unlock the buffer */ V(&sp->slots); /* Announce available slot */ return item; } /* $end sbuf_remove */ /* $end sbufc */ 37
38 Concurrent server based on Prethreading Concurrent server: creating a new thread for each new client. DisAdv: Nontrivial cost of creating a new thread for each new client Prethreaded Concurrent Server Server consists of main thread and a set of worker threads Main thread repeatedly accepts connection requests from clients and places the resulting connected descriptors in a shared buffer. Each worker thread repeatedly removes a descriptors from the buffer, services the client and then waits for the next descriptors Refer: echoservert_pre.c and echo_cnt.c 38
39 39 Organization of a prethreaded concurent server: A set of existing threads repeatedly remove and process connected descriptions from a shared buffer
40 Concurrent server based on Prethreading (cont) SBUF package is used to implement a prethreaded concurrent server echo server Initialize buffer sbuf Main thread creates the set of worker threads Enters the infinite loop, accepting connection requests and inserting resulting connectioned descriptors in sbuf. Each worker thread waits until it is able to remove a connected descriptor from the buffer and calls the echo_cnt function to eacho client input Accesses to the shared byte_cnt variable are protected by P and V operations. 40
41 Event-driven programs based on threads Concurrent prethreaded server can be an eventdriven server with simple state machines for the main and worker thread. Main thread 41 Two states: Waiting for connection request and Waiting for available buffer slot Two I/O events: Connection request arrives and Buffer slot becomes available Two transitions: Accept connection request and Insert buffer item Worker thread One state: Waiting for available buffer slot One I/O event: Buffer slot becomes available One transition: Remove buffer item
42 Producer-Consumer on a Buffer That Holds One Item /* buf1.c - producer-consumer on 1-element buffer */ #include csapp.h #define NITERS 5 void *producer(void *arg); void *consumer(void *arg); struct { int buf; /* shared var */ sem_t full; /* sems */ sem_t empty; } shared; int main() { pthread_t tid_producer; pthread_t tid_consumer; /* initialize the semaphores */ Sem_init(&shared.empty, 0, 1); Sem_init(&shared.full, 0, 0); /* create threads and wait */ Pthread_create(&tid_producer, NULL, producer, NULL); Pthread_create(&tid_consumer, NULL, consumer, NULL); Pthread_join(tid_producer, NULL); Pthread_join(tid_consumer, NULL); } exit(0); 42
43 Producer-Consumer (cont) Initially: empty = 1, full = 0. /* producer thread */ void *producer(void *arg) { int i, item; for (i=0; i<niters; i++) { /* produce item */ item = i; printf("produced %d\n", item); /* consumer thread */ void *consumer(void *arg) { int i, item; for (i=0; i<niters; i++) { /* read item from buf */ P(&shared.full); item = shared.buf; V(&shared.empty); } /* write item to buf */ P(&shared.empty); shared.buf = item; V(&shared.full); } return NULL; } /* consume item */ printf("consumed %d\n", item); } return NULL; 43
44 Thread Safety Functions called from a thread must be thread-safe. We identify four (non-disjoint) classes of thread-unsafe functions: Class 1: Failing to protect shared variables. Class 2: Relying on persistent state across invocations. Class 3: Returning a pointer to a static variable. Class 4: Calling thread-unsafe functions. 44
45 Thread-Unsafe Functions Class 1: Failing to protect shared variables. Relatively easy to make thread-safe Fix: Use P and V semaphore operations. Issue: Synchronization operations will slow down code. Example: goodcnt.c 45
46 Thread-Unsafe Functions (cont) Class 2: Relying on persistent state across multiple function invocations. rand(): repeatedly from from single thread, same sequence of numbers, not if multiple threads are calling it Random number generator relies on static state Fix: Rewrite function so that caller passes in all necessary state. /* rand - return pseudo-random integer on */ int rand(void) { static unsigned int next = 1; next = next* ; return (unsigned int)(next/65536) % 32768; } /* srand - set seed for rand() */ void srand(unsigned int seed) { next = seed; } Thread-unsafe pseudorandom number generator 46
47 Thread-Unsafe Functions (cont) Class 3: Returning a ptr to a static variable. Such function from concurrent threads, results used by one thread will be overwritten by another thread Fixes: Rewrite code so caller passes pointer to struct.» Issue: Requires changes in caller and callee. 2. Lock-and-copy Each call lock mutex, call thread-unsafe function, dynamically allocate memory, copy result and then unlock Issue: Requires only simple changes in caller (and none in callee) However, caller must free memory. struct hostent *gethostbyname(char name) { static struct hostent h; <contact DNS and fill in h> return &h; } hostp = Malloc(...)); gethostbyname_r(name, hostp); struct hostent *gethostbyname_ts(char *p) { struct hostent *q = Malloc(...); P(&mutex); /* lock */ p = gethostbyname(name); *q = *p; /* copy */ V(&mutex); return q; } Thread-safe wrapper for gethostnamebyname() uses the lock-and-copy technique to call a Class 2 thread-unsafe function
48 Thread-Unsafe Functions Class 4: Calling thread-unsafe functions. Calling one thread-unsafe function makes an entire function thread-unsafe. If a function f calls a thread-unsafe function g, is f threadunsafe? If g is a class 2 function that relies on state across multiple invocations, then f is also thread-unsafe and there is no recourse of rewriting g. If g is a class 1 or 3 function, then f can still be thread-safe it your protect the call site and any resulting shared data with a mutex. Fix: Modify the function so it calls only thread-safe functions We used lock-and-copy to write a thread-safe function that calls a thread-unsafe function (previous slide) 48
49 Thread-Safe Library Functions All functions in the Standard C Library (at the back of your K&R text) are thread-safe. Examples: malloc, free, printf, scanf Most Unix system calls are thread-safe, with a few exceptions: Thread-unsafe function Class Reentrant version asctime 3 asctime_r ctime 3 ctime_r gethostbyaddr 3 gethostbyaddr_r gethostbyname 3 gethostbyname_r inet_ntoa 3 (none) localtime 3 localtime_r rand 2 rand_r 49
50 Reentrant Functions A function is reentrant iff it accesses NO shared variables when called from multiple threads. Do not reference any shared data when called by multiple threads Reentrant functions are a proper subset of the set of thread-safe functions. All functions Thread-safe functions Reentrant functions Thread-unsafe functions The set of reentrant functions if a proper subset of the threadsafe functions. NOTE: The fixes to Class 2 and 3 thread-unsafe functions require modifying the function to make it reentrant. 50
51 Reentrant Functions (cont) Example of reentrant version of the rand function. Here static next variable is replaced with a pointer that is passed in by the caller int rand_r(unsigned int *nextp) { *nextp = *nextp * ; return (unsigned int) (*nextp / 65536) % 32768; } Is it possible to inspect the code of a function and declare a priori that it is reentrant?... It depends! If all function arguments are passed by value (e.g. no pointers) and all data references are to local automatic stack variables (i.e. no references to static or global variables) then the function is explicitly reentrant, we can assert its reentrancy regardless of how it is called. 51
52 Reentrant Functions (cont) If we allow some parameters in explicitly reentrant function to be passed by reference (allow them to pass pointers) then we have an implicitly reentrant function; 52 in the sense that it is only reentrant if the calling threads are careful to pass pointers to nonshared data, e.g. rand_r() It is important to realize that reentrancy is sometimes a property of both the caller and the callee, and not only the callee alone. Thread-unsafe functions listed earlier are of the class 3 variety and return a pointer to a static variable. Use lock-and-copy approach, but it will slow down the execution of a program Lock-and-copy will not work for Class 2 thread-unsafe functions such as rand() which relies on static state across calls Unix systems provide reentrant versions of most threadunsafe functions, such functions end with _r suffix. These functions are poorly documented.
53 Races A race occurs when the correctness of the program depends on one thread reaching point x before another thread reaches point y. Races usually occur because programmers assume that threads will take some particular trajectory through the execution state space, forgetting the golden rule that threaded programs must work correctly for any feasible trajectory. race.c: the main thread creates four peer threads and passes pointer to a unique integer ID to each one. Each peer thread copies the ID passed in its argument to a local variable, and then prints a message containing the ID. 53
54 Races (cont) race.c: /* a threaded program with a race */ int main() { pthread_t tid[n]; int i; for (i = 0; i < N; i++) Pthread_create(&tid[i], NULL, thread, &i); for (i = 0; i < N; i++) Pthread_join(tid[i], NULL); exit(0); } /* thread routine */ void *thread(void *vargp) { int myid = *((int *)vargp); printf("hello from thread %d\n", myid); return NULL; } 54
55 Races (cont) The problem is caused by a race between each peer thread and the main thread. When the main thread creates a peer thread: 55 Pthread_create(&tid[i], NULL, thread, &i); It passes a pointer to the local stack variable i. At this point the race is between the next call to Pthread_create and the deferencing and assignment of the argument in line : int myid = *((int *)vargp); If peer thread executes above code before main thread creates next peer thread, then myid variable will get correct ID. Otherwise it will contain ID of some other thread.
56 Races (cont) Correct answer depends on how the kernel schedules the execution of threads. It may differ from system to system. Solution: We can dynamically allocate a separate block for each integer ID and pass the thread routine a pointer to this block: for (i = 0; i < N; i++) {. *ptr = i; ptr = Malloc(sizeof(int)); Pthread_create(&tid[i], NULL, thread, ptr); } void *thread(void *vargp) { Free(vargp); } int myid = *((int *)vargp); Note: Do not forget to free the block in order to avoid memory leak. 56
57 Deadlock Thread 2 V(s) V(t) P(s) P(t) forbidden region for s deadlock region forbidden region for t deadlock state Locking introduces the potential for deadlock: waiting for a condition that will never be true. Any trajectory that enters the deadlock region will eventually reach the deadlock state, waiting for either s or t to become nonzero. Other trajectories luck out and skirt the deadlock region. P(s) Initially, s=t=1 P(t) V(s) V(t) Thread 1 Unfortunate fact: deadlock is often non-deterministic. 57
58 Deadlock (cont) When binary semaphores are used, following rule can be applied: Mutex lock ordering rule: A program is deadlock-free if, for each pair of mutexes (s, t) in the program, each thread that holds both s and t simultaneously locks them in the same order. Lock s first, then t in each thread. 58
59 Threads Summary Threads provide another mechanism for writing concurrent programs. Threads are growing in popularity Somewhat cheaper than processes. Easy to share data between threads. However, the ease of sharing has a cost: Easy to introduce subtle synchronization errors. Tread carefully with threads! For more info: D. Butenhof, Programming with Posix Threads, Addison- Wesley,
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! 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 informationfor (i = 0; i < 2; i++)
53 The course that gives CMU its Zip! Programming with Threads Dec 5, Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races and deadlocks
More informationShared Variables in Threaded C Programs. Systemprogrammering Föreläsning 11 Programming with Threads
Systemprogrammering Föreläsning Programming with Threads Topics Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared variables?! The answer is not as simple
More informationSynchronization April 29, 2008
5-3 The course that gives CMU its Zip! Synchronization April 9, 008 Topics Shared variables The need for synchronization Synchronizing with semaphores Thread safety and reentrancy Races and deadlocks class5.ppt
More informationSynchronization: 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 informationSynchronization: Basics
Synchronization: Basics 53: Introduction to Computer Systems 4 th Lecture, April 8, 7 Instructor: Seth Copen Goldstein, Franz Franchetti Today Threads review Sharing Mutual exclusion Semaphores Traditional
More informationCarnegie Mellon 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 informationCarnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition
Synchronization: Basics 53: Introduction to Computer Systems 4 th Lecture, November 6, 7 Instructor: Randy Bryant Today Threads review Sharing Mutual exclusion Semaphores 3 Traditional View of a Process
More informationSynchronization: Basics
Synchronization: Basics CS 485G6: Systems Programming Lecture 34: 5 Apr 6 Shared Variables in Threaded C Programs Question: Which variables in a threaded C program are shared? The answer is not as simple
More informationCarnegie Mellon. 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 informationLecture #24 Synchronization
Lecture #24 Synchronization 8-600: Foundations of Computer Systems November 27, 207 Today Sharing Mutual exclusion Semaphores 2 Shared Variables in Threaded C Programs Question: Which variables in a threaded
More informationToday. Threads review Sharing Mutual exclusion Semaphores
SYNCHRONIZATION Today Threads review Sharing Mutual exclusion Semaphores Process: Traditional View Process = process context + code, data, and stack Process context Program context: Data registers Condition
More informationThe course that gives CMU its Zip! Concurrency II: Synchronization Nov 14, 2000
5-3 The course that gives CMU its Zip! Concurrency II: Synchronization Nov 4, 000 Topics Progress graphs Semaphores Mutex and condition variables Barrier synchronization Timeout waiting A version of badcnt.c
More informationCarnegie Mellon Concurrency and Synchronization
Concurrency and Synchronization CMPSCI 3: Computer Systems Principles int pthread_join (pthread_t thread, void **value_ptr) { int result; ptw3_thread_t * tp = (ptw3_thread_t *) thread.p; if (NULL == tp
More informationSynchroniza+on: Advanced
Synchroniza+on: Advanced 15-213: Introduc;on to Computer Systems 25 th Lecture, Nov. 24, 2015 Instructors: Randal E. Bryant and David R. O Hallaron 1 Review: Semaphores Semaphore: non- nega+ve global integer
More informationConcurrent Programming
Concurrent Programming 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 informationProcess Synchroniza/on
Process Synchroniza/on Andrew Case Slides adapted from Mohamed Zahran, Clark Barre9, Jinyang Li, Randy Bryant and Dave O Hallaron Topics Sharing data Race condi/ons Mutual exclusion and semaphores Sample
More informationConcurrency on x86-64; Threads Programming Tips
Concurrency on x86-64; Threads Programming Tips Brad Karp UCL Computer Science CS 3007 22 nd March 2018 (lecture notes derived from material from Eddie Kohler, David Mazières, Phil Gibbons, Dave O Hallaron,
More informationPthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.
1 Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Last Class Review 2 ANSI/IEEE POSIX1003.1-95 Standard Thread management Work directly on threads
More informationPthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Pthreads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The Pthreads API ANSI/IEEE POSIX1003.1-1995 Standard Thread management Work directly on
More informationProxy: Concurrency & Caches
Proxy: Concurrency & Caches Elie Krevat (with wisdom from past terms) Outline Proxy Lab logistics Concurrency and multi-threading Synchronization with semaphores Caching objects in your proxy Proxy Lab
More informationConcurrency. Alan L. Cox Some slides adapted from CMU slides
Concurrency Alan L. Cox alc@rice.edu Some slides adapted from CMU 15.213 slides Objectives Be able to apply three techniques for achieving concurrency Process Thread Event-driven Be able to analyze the
More informationCSC 1600: Chapter 6. Synchronizing Threads. Semaphores " Review: Multi-Threaded Processes"
CSC 1600: Chapter 6 Synchronizing Threads with Semaphores " Review: Multi-Threaded Processes" 1 badcnt.c: An Incorrect Program" #define NITERS 1000000 unsigned int cnt = 0; /* shared */ int main() pthread_t
More informationCS3733: Operating Systems
Outline CS3733: Operating Systems Topics: Synchronization, Critical Sections and Semaphores (SGG Chapter 6) Instructor: Dr. Tongping Liu 1 Memory Model of Multithreaded Programs Synchronization for coordinated
More informationCS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio
CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio Fall 2017 1 Outline Inter-Process Communication (20) Threads
More informationExample. Example. Threading Language and Support. CS528 Multithreading: Programming with Threads. The boss/worker model. Thread Programming models
Threading Language and Support CS528 Multithreading: Programming with Threads A Sahu Dept of CSE, IIT Guwahati Pthread: POSIX thread Popular, Initial and Basic one Improved Constructs for threading c++
More informationMultithreading Programming II
Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure
More informationCS 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 informationThe course that gives CMU its Zip! Concurrency I: Threads April 10, 2001
15-213 The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing data
More informationIntroduction to Threads
Computer Systems Introduction to Threads Race Conditions Single- vs. Multi-Threaded Processes Process Process Thread Thread Thread Thread Memory Memory Heap Stack Heap Stack Stack Stack Data Data Code
More informationpthreads 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 informationCS 33 Week 7. Section 1G, Spring 2015 Prof. Eggert (TA: Eric Kim) v1.0
CS 33 Week 7 Section 1G, Spring 2015 Prof. Eggert (TA: Eric Kim) v1.0 Announcements Lab 3 was due Wednesday ("smashing" lab) May be on midterm 2! HW 5 out! Due: May 29th (2 weeks from now) Midterm 2 on
More informationKING FAHD UNIVERSITY OF PETROLEUM & MINERALS. Information and Computer Science Department. ICS 431 Operating Systems. Lab # 9.
KING FAHD UNIVERSITY OF PETROLEUM & MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 9 Semaphores Objectives: In this lab, we will use semaphore to solve various synchronization
More informationConcurrent Programming
Concurrent Programming CS 485G-006: Systems Programming Lectures 32 33: 18 20 Apr 2016 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking
More informationComputer Systems Laboratory Sungkyunkwan University
Concurrent Programming Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int main (int argc, char *argv[]) {... listenfd = socket(af_inet, SOCK_STREAM, 0); bzero((char
More informationNote: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer Problem.
CSCI-375 Operating Systems Lab #5 Semaphores, Producer/Consumer Problem October 19, 2016 Note: The following (with modifications) is adapted from Silberschatz (our course textbook), Project: Producer-Consumer
More informationSistemi in tempo reale Anno accademico
Sistemi in tempo reale Anno accademico 2006-2007 Concorrenza - II Giuseppe Lipari http://feanor.sssup.it/~lipari Scuola Superiore Sant Anna Outline 1 Introduction to concurrency 2 Models of concurrency:
More informationCS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization
CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It
More informationCS 5523: Operating Systems
CS 5523: Operating Systems Instructor: Dr. Tongping Liu Midterm Exam: Oct 6, 2015, Tuesday 7:15pm 8:30pm CS5523: Operating Systems @ UTSA 1 Lecture1: OS Overview Operating System: what is it?! Evolution
More informationCS 5523 Operating Systems: Thread and Implementation
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationCSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks
CSci 4061 Introduction to Operating Systems Synchronization Basics: Locks Synchronization Outline Basics Locks Condition Variables Semaphores Basics Race condition: threads + shared data Outcome (data
More informationProcess 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 informationConcurrent Programming is Hard! Concurrent Programming. Reminder: Iterative Echo Server. The human mind tends to be sequential
Concurrent Programming is Hard! Concurrent Programming 15 213 / 18 213: Introduction to Computer Systems 23 rd Lecture, April 11, 213 Instructors: Seth Copen Goldstein, Anthony Rowe, and Greg Kesden The
More informationLecture #23 Concurrent Programming
Lecture #23 Concurrent Programming Nov. 20, 2017 18-600 Foundations of Computer Systems 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking
More informationCS Operating Systems: Threads (SGG 4)
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationSynchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han
Synchronization CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Announcements HW #3 is coming, due Friday Feb. 25, a week+ from now PA #2 is coming, assigned about next Tuesday Midterm is tentatively
More informationThreads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr.
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate
More informationCarnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition
Carnegie Mellon 1 Concurrent Programming 15-213: Introduction to Computer Systems 23 rd Lecture, Nov. 13, 2018 2 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time
More informationConcurrent Server Design Multiple- vs. Single-Thread
Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),
More informationConcurrent Programming
Concurrent Programming Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int
More informationTotal Score is updated. The score of PA4 will be changed! Please check it. Will be changed
Announcement Total Score is updated Please check it Will be changed The score of PA4 will be changed! 1 Concurrent Programming Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Sanghoon Han(sanghoon.han@csl.skku.edu)
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution
More informationConcurrent Programming
Indian Institute of Science Bangalore, India भ रत य व ज ञ न स स थ न ब गल र, भ रत SE 292: High Performance Computing [3:0][Aug:2014] Concurrent Programming Yogesh Simmhan Adapted from Intro to Concurrent
More informationConcurrent Programming
Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently
More informationSynchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks
Synchronization II Today Condition Variables Semaphores Monitors and some classical problems Next time Deadlocks Condition variables Many times a thread wants to check whether a condition is true before
More informationSynchronization 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 informationPOSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff
POSIX threads CS 241 February 17, 2012 Copyright University of Illinois CS 241 Staff 1 Recall: Why threads over processes? Creating a new process can be expensive Time A call into the operating system
More informationThreads. lightweight processes
Threads lightweight processes 1 Motivation Processes are expensive to create. It takes quite a bit of time to switch between processes Communication between processes must be done through an external kernel
More informationApproaches to Concurrency
PROCESS AND THREADS Approaches to Concurrency Processes Hard to share resources: Easy to avoid unintended sharing High overhead in adding/removing clients Threads Easy to share resources: Perhaps too easy
More informationANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT
ANKARA UNIVERSITY COMPUTER ENGINEERING DEPARTMENT BLM334-COM334 PROJECT Due date: 08.05.2013 Lab Hours You re expected to implement Producer-Consumer Problem that is described below. (Any form of cheating
More informationPre-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 informationConcurrent Programming
Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently
More informationWeek 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 informationInterprocess 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 informationDealing with Issues for Interprocess Communication
Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed
More informationPOSIX Threads. Paolo Burgio
POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the
More informationRecitation 14: Proxy Lab Part 2
Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization 2 ProxyLab ProxyLab is due in 1 week. No grace days Late days allowed (-15%) Make sure to submit
More informationHPCSE - I. «Introduction to multithreading» Panos Hadjidoukas
HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -
More informationCS 261 Fall Mike Lam, Professor. Threads
CS 261 Fall 2017 Mike Lam, Professor Threads Parallel computing Goal: concurrent or parallel computing Take advantage of multiple hardware units to solve multiple problems simultaneously Motivations: Maintain
More informationData Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017
Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread
More informationCS510 Operating System Foundations. Jonathan Walpole
CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking
More informationCarnegie Mellon Performance of Mul.threaded Code
Performance of Mul.threaded Code Karen L. Karavanic Portland State University CS 410/510 Introduc=on to Performance Spring 2017 1 Using Selected Slides from: Concurrent Programming 15-213: Introduc=on
More informationSynchronization 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 information15-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 informationConcurrent Servers Dec 2, 2009"
Concurrent Servers Dec 2, 2009" Administrivia" 2! Iterative Servers" client 1! server! client 2! call connect ret connect call read ret read close call accept" ret accept" write close call accept" ret
More information[537] Semaphores. Tyler Harter
[537] Semaphores Tyler Harter Producer/Consumer Problem Producers generate data (like pipe writers). Consumers grab data and process it (like pipe readers). Producer/consumer problems are frequent in systems.
More informationConcurrent 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 informationConcurrent Programming
Concurrent Programming 15-213 / 18-213: Introduc2on to Computer Systems 23 rd Lecture, Nov. 14, 2013 Instructors: Randy Bryant, Dave O Hallaron, and Greg Kesden 1 Concurrent Programming is Hard! The human
More informationCS333 Intro to Operating Systems. Jonathan Walpole
CS333 Intro to Operating Systems Jonathan Walpole Threads & Concurrency 2 Threads Processes have the following components: - an address space - a collection of operating system state - a CPU context or
More informationRecitation 14: Proxy Lab Part 2
Recitation 14: Proxy Lab Part 2 Instructor: TA(s) 1 Outline Proxylab Threading Threads and Synchronization PXYDRIVE Demo 2 ProxyLab Checkpoint is worth 1%, due Thursday, Nov. 29 th Final is worth 7%, due
More informationLocks and semaphores. Johan Montelius KTH
Locks and semaphores Johan Montelius KTH 2018 1 / 40 recap, what s the problem : # include < pthread.h> volatile int count = 0; void * hello ( void * arg ) { for ( int i = 0; i < 10; i ++) { count ++;
More informationLecture 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 informationreal time operating systems course
real time operating systems course 4 introduction to POSIX pthread programming introduction thread creation, join, end thread scheduling thread cancellation semaphores thread mutexes and condition variables
More informationThread. Disclaimer: some slides are adopted from the book authors slides with permission 1
Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast
More informationParallel Programming Languages COMP360
Parallel Programming Languages COMP360 The way the processor industry is going, is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight,
More informationConcurrent Programming. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Concurrent Programming Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int main (int argc, char *argv[]) {... listenfd = socket(af_inet,
More informationAnnouncements. Class feedback for mid-course evaluations Receive about survey to fill out until this Friday
Announcements Project 2: Part 2a will be graded this week Part 2b take longer since we compare all graphs Project 3: Shared memory segments Linux: use shmget and shmat across server + client processes
More informationTHREADS: (abstract CPUs)
CS 61 Scribe Notes (November 29, 2012) Mu, Nagler, Strominger TODAY: Threads, Synchronization - Pset 5! AT LONG LAST! Adversarial network pong handling dropped packets, server delays, overloads with connection
More informationcall connect call read call connect ret connect call fgets Client 2 blocks waiting to complete its connection request until after lunch!
15-213 The course that gives CMU its Zip! Concurrent Servers December 4, 2001 Topics Limitations of iterative servers Process-based concurrent servers Threads-based concurrent servers Event-based concurrent
More informationOutline. 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 informationCS Operating Systems
CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,
More informationCS Operating Systems
CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,
More informationCS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017
CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution
More informationProcesses Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.
Processes Prof. James L. Frankel Harvard University Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved. Process Model Each process consists of a sequential program
More informationQ1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100
ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume
More informationW4118 Operating Systems. Instructor: Junfeng Yang
W4118 Operating Systems Instructor: Junfeng Yang Outline Semaphores Producer-consumer problem Monitors and condition variables 2 Semaphore motivation Problem with lock: mutual exclusion, but no ordering
More informationProgramming 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 informationCS533 Concepts of Operating Systems. Jonathan Walpole
CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?
More information