Warning: To compile program certain operating system needs you to expressly enable dynamic linkage of pthread lib. To compile a program which uses pthread functions you then need to configure gcc to dynamically link with pthread lib using the following command:
gcc my_file.c -o my_executable -l pthread
First steps with Threads
Given the following source code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
static void *task_a(void *p_data) {
puts("Hello world from task_a");
return NULL;
}
int main(void) {
puts("Main program init");
pthread_t ta;
pthread_create(&ta, NULL, task_a, NULL);
puts("Thread started");
sleep(5);
puts("Main program end");
return EXIT_SUCCESS;
}
- Write a program which:
- Creates and runs a thread that is printing
"Hello again"every seconds in a infinite loop. - Then waits for 10 seconds (
sleepfunction) before ending normally.
- Creates and runs a thread that is printing
- What is happening when the main program ends ?
- What is the difference with a
forksystem call ? Explain. - Replace the
sleep(10)function bypthread_join(ta, NULL).- What is happening ?
- What is the goal of the
pthread_joinfunction ?
It’s now your turn to play with threads
Program creation
Write a program that launch two threads. Each thread is printing a random number (Click Here for a code sample) every seconds for the first one and every two seconds for the second one. The program ends when a key is hit in the keyboard(Click here for a code sample).
Refactor your code
Modify the program to use the same function for both threads.
Ok now let’s play with a hundred threads !
Write a program which creates 100 threads where the function:
- Increment a static variable to indicate the active thread count.
- Get a random number between 1 and 5 (use
rand() % 5 + 1) - Writes to STDOUT that the thread XXX (value incremented) is going to sleep for n seconds (random value)
- Sleeps for n seconds (random value)
- Ends by printing “Thread XXX just ended.”
The main program is going to wait for every other threads.
Code samples
Random Number
srand(time(NULL)); // Initialize Random
int random_value = rand() % 10 + 1; // Random value for 1 to 10
Detect Keyboard Hit
getchar() // Waits for a keyboard key hit