{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture20-multithreading-semaphores

Lecture20-multithreading-semaphores - Announcements Project...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CS 3214 Computer Systems Godmar Back Lecture 20 Announcements Project 5 due Nov 16 Exercise 7 due Nov 18 CS 3214 Fall 2011 MULTI-THREADING CS 3214 Fall 2011 Coordinating Multiple Threads Aside from coordinating access to shared items, threads may need to communicate about events – “has event A already happened in another thread?” – aka “precedence constraint”, or “scheduling constraint” • Do B after A Do B after A Must do so – Correctly (never miss that event A has occurred when in fact it has) – Efficiently Don’t waste resources in the process Don’t unnecessarily delay notification of event A CS 3214 Fall 2011 int main() { int i, N = 2; pthread_t t[N]; srand(getpid()); pthread_create(&t[1], NULL, thread2, NULL); pthread_create(&t[0], NULL, thread1, NULL); for (i = 0; i < N; i++) pthread_join(t[i], NULL); return 0; int coin_flip; static void * thread1(void *_) { coin_flip = rand() % 2; printf("Thread 1: flipped coin %d\n", coin_flip); return NULL; } static void * Q.: How can thread2 make sure that ‘coin_flip’ has occurred before printing its outcome? CS 3214 Fall 2011 } static void thread2(void *_) { printf("Thread 2: flipped coin %d\n", coin_flip); return NULL; } Thread 2 could “busy- wait” – spin until thread 1 completes the coin flip. Exceptions not withstanding, this is practically never an acceptable solution . static void * thread2(void * ) int coin_flip; volatile bool coin_flip_done; static void * thread1(void *_) { coin_flip = rand() % 2; coin_flip_done = true; printf("Thread 1: flipped coin %d\n", coin_flip); return NULL; } The somewhat less wasteful -wastes CPU CS 3214 Fall 2011 static void thread2(void _) { /* Thread 2 spins, "busy-waits" until the coin flip is done. * This is an unacceptable solution. Bad for the planet, too. */ while (!coin_flip_done) continue; printf("Thread 2: flipped coin %d\n", coin_flip); return NULL; } variant of busy-waiting: while (!coin_flip_done) sched_yield(); is not acceptable, either . cycles - is fragile (volatile needed when using –O) - does not document semantics
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon