In this assignment, you will take a non thread-safe version of a hash table and modify it so that it correctly supports running with multiple threads. This **does not involve xv6**; xv6 doesn't currently support multiple threads of execution, and while it is possible to do parallel programming with processes, it’s tricky to arrange access to some shared resource. Instead you will do this assignment on a multicore machine. Essentially any desktop machine made in the past 7 years or so should have multiple cores.
Start by downloading the attached file, parallel_hashtable.c to your local machine and you will compile it with the following command:
[main] Retrieved 65634/100000 keys in 0.792488 seconds
Play around with the number of threads. You should see that, in general, the program gets faster as you add more threads up until a certain point. However, sometimes items that get added to the hash table get lost.
Part 1
Find out under what circumstances entries can get lost. Update `parallel_hashtable.c` so that `insert` and `retrieve` do not lose items when run from multiple threads. Verify that you can now run multiple threads without losing any keys. Compare the speedup of multiple threads to the version that uses no mutex -- you should see that there is some overhead to adding a mutex.
You will probably need:
pthread_mutex_t lock; // declare a lock pthread_mutex_init(&lock, NULL); // initialize the lock pthread_mutex_lock(&lock); // acquire lock pthread_mutex_unlock(&lock); // release lock
We will see this API in class this week. You can also use `man` to get more documentation on any of these.
Once you have a solution to this problem save it to a file called 'parallel_mutex.c'
Part 2
Make a copy of `parallel_mutex.c` and call it `parallel_spin.c`. Replace all of the mutex APIs with the spinlock APIs in pthreads. The spinlock APIs in pthreads are:
Do you see a change in the timing? Did you expect that? Write down the timing differences and your thoughts in a comment in your source file.
Part 3
For part 3 continue working with **'parallel_mutex.c' **
Does retrieving an item from the hash table require a lock? Update the code so that multiple `retrieve` operations can run in parallel.
Part 4
For part 4 continue working with 'parallel_mutex.c'
Update the code so that some `insert` operations can run in parallel.
Hint: if two inserts are being done on *different* buckets in parallel, is a lock needed? What are the shared resources that need to be protected by mutexes?