Four threads each call the function below, and main calls pthread_join on all four before printing total. The intended result is 400000, but a test run prints a smaller number. Assume all pthread calls succeed.
long total = 0; /* global */ void *worker(void *arg) { pthread_mutex_t lock; pthread_mutex_init(&lock, NULL); for (int i = 0; i < 100000; i++) { pthread_mutex_lock(&lock); total++; pthread_mutex_unlock(&lock); } pthread_mutex_destroy(&lock); return NULL; }
Which statement correctly identifies the synchronization error behind the incorrect result?
Declaring total as volatile long would fix the program, because the increment would then happen in one atomic step.
Another thread can slip in between pthread_mutex_lock and pthread_mutex_unlock because the lock is released on every iteration.
Each thread creates its own mutex on its own stack, so the locks do not provide mutual exclusion for accesses to the shared total.
The loop variable i is shared by the four threads, so some threads skip iterations and never increment total.
Unlock full course notes by signing up
Speedup of a partly parallel analysis program
A single-threaded data-analysis program takes 120 s per run. Of that, 30 s goes to loading input and merging results, which must stay serial, and 90 s goes to a loop whose iterations are independent. You split the loop evenly across 8 threads on a machine with 8 idle cores, and you ignore threading overhead. What speedup over the single-threaded version do you get? Give the answer as a plain number to two decimal places.
Tracing a lost update step by step
A shared integer x starts at 7. Threads A and B each execute x++, which the processor performs as three steps: load x into the thread's register, add 1 to the register, then store the register back to x. The scheduler runs the six steps in the order shown. Fill in each thread's register value and the value of x in memory after each step, as integers.
Balancing unequal tasks across workers
Eight independent tasks, A through H, take 9, 7, 5, 3, 1, 3, 5, and 7 ms respectively on one worker. Four identical workers start simultaneously. Each worker executes its assigned tasks sequentially. Assume enough processor cores for all workers, unchanged task times during parallel execution, and no scheduling or synchronization costs.
Compare these assignments:
Contiguous assignment: worker 1 receives A and B; worker 2 receives C and D; worker 3 receives E and F; worker 4 receives G and H.
When additional workers stop helping
An image-processing batch contains NNN independent, indivisible tasks. Each task takes exactly 0.80 ms on one worker. The original serial implementation executes tasks consecutively and has no additional costs.
A proposed parallel implementation uses ppp identical workers and has these measured costs:
Before any worker starts, the main thread schedules all tasks, taking 0.05 ms per task.