Search
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.
-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
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void* ThreadFunction(void *arguments){ int* pval = arguments; int val = pval[0]; printf("Hello from thread: %i\n", val); return NULL; } int main() { printf("Remember, as all the threads are running in parallel, the order of the following lines may change each time you run the program!\n"); int* ids = malloc(3*sizeof(int)); ids[0] = 1; ids[1] = 2; ids[2] = 3; pthread_t t1, t2, t3; pthread_create(&t1, NULL, ThreadFunction, &ids[0]); pthread_create(&t2, NULL, ThreadFunction, &ids[1]); pthread_create(&t3, NULL, ThreadFunction, &ids[2]); printf("Main thread is here.\n"); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); free(ids); return 0; }