ILWC Privacy Statement About ILWC
A little multi threading in C
2019-02-02 22:30:58
2019-02-03 23:00:00
2019-03-03 23:00:00
For some tasks I need a little programming. And how can you program best...with C. (If it can't be done in C you really need to turn to the magicians of assembly)

One of the things I need for someassignment was multithreading. All in all it's not that difficult, but the debugging is a hell (wich thread should I look at(?)).

So I wrote a small example of how a (very very) basic multi threaded program could look like.
#include pthread.h>    (I left out the < since that gave some formatting issues)
#include stdio.h>      (I left out the < since that gave some formatting issues)

void * f(void * x_in){
  int * x_local=(int *) x_in;

  (int *) ++x_in;

  return NULL;

int main(int argc, char ** argv){
  int x=0;
  int n=5;
  pthread_t pt;

  printf("Start main: %i\n", x);
  while (n>0){
    pthread_create(&pt, NULL, f, &x);
    pthread_join(pt, NULL);
  printf("Stop main: %i\n", x);

  return 0;
The main program initializes a few variables and then in a loop creates the threads.
The first argument is the thread control structure you get back from the thread creation.
The second parameter are thread attributes which are not discussed now.
The third parameter is the function which is the starting point for the thread. Take care...this function should be void * (a pointer to a void).
The fourth parameter is the address of the variable you would like to feed to the function. And now compile:
[martijn@radijs graph]$ gcc -pthread threads.c -o threads -Wall
And run:
[martijn@radijs graph]$ ./threads
Start main: 0
Stop main: 5
[martijn@radijs graph]$