Thread Synchronization

Lab exercises for February 26th. Due Feb 27th

The goals for this assignment are:

  • Understanding the pthread library

  • Using synchronization primitives

We will use the same repository as last week: Labs Repo. Do a git pull to get the lab basecode.

1. Dining Philosophers

Edit the file, dining_philosophers.c, to avoid deadlock.

When you run the basecode, your program will run for a while but then deadlock. For example,

$ ./dining_philosophers
2 is hungry
2 is eating
4 is hungry
3 is thinking
3 is thinking
2 is thinking
1 is eating
3 is hungry
2 is hungry
1 is hungry

Requirements:

  • Add the fix from class to fix the program and verify that it works.

2. Mountainview Village

In the remote town of Mountainview Village, there is a single lane bridge that connects a popular overlook with a quaint town center with shops and cafes. During peak season, tourists spend the day driving back and forth across the bridge, alternating between fresh air and inspiring views at the outlook platform and coffee, ice cream, and snacks at the town center.

In the file, bridge.c, you will find a simulation of summer tourists. Each tourist is simulated with a thread. The bridge is modeled as a shared, global resource. If two cars simultaneously try to drive in opposite directions on the bridge, we have a terrible accident. The bridge explodes and any cars on the bridge plummet to the rapids below.

Edit the file, bridge.c, to safely simulate N tourists spending the day in Mountainview Village.

  • prevent deadlocks where no one takes the bridge

  • prevent accidents where cars travel in both directions at once

For example, here is a single tourist.

$ ./bridge 1 10
Tourist 0 takes their 0/10 trip towards Outlook
Tourist 0 takes their 1/10 trip towards Town
Tourist 0 takes their 2/10 trip towards Outlook
Tourist 0 takes their 3/10 trip towards Town
Tourist 0 takes their 4/10 trip towards Outlook
Tourist 0 takes their 5/10 trip towards Town
Tourist 0 takes their 6/10 trip towards Outlook
Tourist 0 takes their 7/10 trip towards Town
Tourist 0 takes their 8/10 trip towards Outlook
Tourist 0 takes their 9/10 trip towards Town

But running with multiple tourists, we quickly see a problem.

$ ./bridge 2 10
Tourist 1 takes their 0/10 trip towards Town
Tourist 0 takes their 0/10 trip towards Outlook
bridge: bridge.c:38: Move: Assertion `bridge.num_on_bridge[(bridge.direction+1)%2] == 0' failed.
bridge: bridge.c:38: Move: Assertion `bridge.num_on_bridge[(bridge.direction+1)%2] == 0' failed.
Aborted (core dumped)

Requirements:

  • Your program must leave the asserts which verify that the safety constraints are enforced.

  • You should use conditional variables and mutex to synchronize the threads that represent each tourist.