Search
The following code runs the example function in a separate thread using the POSIX pthread library, see documentation. 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.
-lpthread
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.
pthread_create
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
Extension tasks
pthread_t thread1
pthread_t thread2
Exercise 3
The longest file was ***.txt, which has 162 characters