FRI-OS
example/posix/pthreads-simple_usage.c

Shows basic usage of the pthread library

//LDFLAGS = -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// Structure storing input data and place for the resultof the computation
struct computation
{
int argument;
unsigned long result;
};
// naive implementation of the fibonacci function
unsigned long fib(int n)
{
if(n < 2) return 1;
else return fib(n-2) + fib(n-1);
}
// the thread's main function
void* calc_fib(void* raw_ptr)
{
// cast the raw pointer to the proper type
computation* c = (computation*)raw_ptr;
// calculate the value of the fibonacci function
// for the specified argument and store it into result
c->result = fib(c->argument);
return (void*)0;
}
int main(int argc, const char* argv[])
{
// get the argument
int arg = (argc>1)?atoi(argv[1]):42;
if(arg <= 0) arg = 42;
// initialize the data for the computation
// NOTE that the object must exist during the whole
// lifetime of the thread
computation comp = {arg, 0};
// start the worker thread
pthread_t worker;
pthread_create(&worker, (pthread_attr_t*)0, calc_fib, (void*)&comp);
// wait for the thread to finish
pthread_join(worker, (void**)0);
// print the result
fprintf(stdout, "fib(%i) = %lu\n", comp.argument, comp.result);
return 0;
}