Search
Previously we covered pthread_mutex_lock and pthread_mutex_unlock. There is also a third locking mechanism: pthread_mutex_trylock. Try lock will not wait until the lock is available, it will return immediately. It will return zero if it acquired the lock, else something else if not (specifically an error code, most commonly a number meaning “Lock is busy”).
Exercise 1: Modify the code from last week. Start by adapting the code to use initialise and destroy the locks with pthread_mutex_init(&mutex, NULL); and pthread_mutex_destroy(&mutex);. Change the locks to use pthread_mutex_trylock instead of pthread_mutex_lock. If the lock cannot be acquired, wait and try again.
Threads are obviously used where we want multiple things to happen at the same time. Therefore they are commonly employed for slow processes like in the following schemes:
The final layout is called a producer-consumer model. It can interact with many buffers in the following way:
if(pthread_mutex_trylock(&lockA) == 0) { //lock was available, modify the data here pthread_mutex_unlock(&lockA); } else if(pthread_mutex_trylock(&lockB) == 0) { //else, try store the data in another buffer pthread_mutex_unlock(&lockB); }
But is this a good idea? Hint: What happens if no locks are available? Think about how we can solve this.
Exercise 2: Create 3 threads which will generate a random integer *once per second*. The threads will loop forever. These will be our producers. They will safely put the random number into one of two global buffers.
There will then be two other threads, our consumers, which will check if there is data in the buffers. If so, they will grab the result, and calculate if it is a prime number, and output the result.