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;
}
  1. Write a program which:
    1. Creates and runs a thread that is printing "Hello again" every seconds in a infinite loop.
    2. Then waits for 10 seconds (sleep function) before ending normally.
  2. What is happening when the main program ends ?
  3. What is the difference with a fork system call ? Explain.
  4. Replace the sleep(10) function by pthread_join(ta, NULL).
    1. What is happening ?
    2. What is the goal of the pthread_join function ?

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:

  1. Increment a static variable to indicate the active thread count.
  2. Get a random number between 1 and 5 (use rand() % 5 + 1)
  3. Writes to STDOUT that the thread XXX (value incremented) is going to sleep for n seconds (random value)
  4. Sleeps for n seconds (random value)
  5. 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