Table of Contents

Lab 08 - Threading Part 2

Trylock Example

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 to use pthread_mutex_trylock instead of pthread_mutex_lock. Use a pair of threads, which will safely modify a global variable. The program will then join them, print the global variable, and close.

Producer-Consumer Model

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 number every second. The threads will loop forever. These will be our producers. They will safely put the random number into one of two buffers.

There will then be two other threads, our consumers, which will check if there is data in the buffers, and if so, print it.

Extension Tasks

ie. int nProducerThreads = 15;