Warning
This page is located in archive.

Lab 09 - Threading

Simple Threading example

The following code runs the example function in a separate thread. The code is being run in 2 places in parallel.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* myThreadFunction(void *arguments){
    printf("Thread running.\n");
    return NULL;
}

int main() {
    pthread_t thread1;
    pthread_create(&thread1, NULL, myThreadFunction, NULL);
    printf("Main Thread.\n");
    pthread_join(thread1, NULL); 
    return 0;
}

You will need to add -lpthread to your compiler instructions.

Exercise 1

Modify the code to create 3 threads. Pass in an ID number to each thread, so you can create the following output:

Thread Running. I am thread: 0
Thread Running. I am the main thread
Thread Running. I am thread: 1
Thread Running. I am thread: 2

The final parameter of pthread_create is a pointer which is passed to your function, so you will need to pass in the ID number in this form.

Mutexes

We can use mutexes to control access to shared variables. The following code shows how a global variable can be modified safely:

pthread_mutex_t lock;
int someVariable = 20;

void* ThreadFunction(void* arguments)
{
    pthread_mutex_lock(&lock); //if multiple threads reach here, only one will pass and the others will wait until it is unlocked, then the next will go
   
    someVariable = 50;

    pthread_mutex_unlock(&lock);

    return NULL;
}

Exercise 2

  • Create an array of several numbers.
  • Create a thread for each value.
  • Create a global “maximum” variable.
  • The threads will test if their number is bigger than the maximum, and if so replace maximum with their value.
  • At the end of the program, print “the biggest number was x”.

Extension tasks

  • Can you populate your array with random values automatically?
  • Can you dynamically create the threads in a for loop (for every value in the array) rather than having pthread_t thread1 and pthread_t thread2?
  • Can you ask the user for the size of the array?

Exercise 3

  • Pass strings into the threads.
  • The strings will be filenames.
  • In the threads, open the file, count how many characters are present, and set the maximum value to this.
  • Use another global variable to record the name of the longest file.
  • When finished, print The longest file was ***.txt, which has 162 characters.
courses/be5b99cpl/labs/lab09.txt · Last modified: 2023/11/22 11:21 by brouggeo