1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// !> A very simple thread example

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

#include <pthread.h>
#include <unistd.h>

#include <assert.h>

void *my_first_thread(void *args) {
  sleep(1);
  int a = *((int *) args);
  fprintf(stderr, "Hello from my first thread: %d\n", a);

  int *result = malloc(sizeof(int));
  *result = a + 1;
  return result;
}

int main(int argc, char **argv) {
  pthread_t th;

  int arg = 42;
  fprintf(stderr, "Starting a thread...\n");
  // run a thread that will hello world and finish
  assert(0 == pthread_create(&th, NULL, my_first_thread, &arg));
  fprintf(stderr, "Started a thread. Waiting for it to finish.\n");

  int *res;
  assert(0 == pthread_join(th, (void **) &res));
  fprintf(stderr, "Done: %d. Exiting.\n", *res);
  return 0;
}