FRI-OS
example/posix/threads-simple_usage.cpp

Shows basic usage of the FRI-OS wrapped POSIX threads

//LDFLAGS = -lpthread
#include <iostream>
#include <cstdlib>
#include <frios/posix.hpp>
// Structure storing input data and place for the result of the computation
struct computation
{
int argument;
unsigned long long result;
};
// naive implementation of the fibonacci function
unsigned long 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 = static_cast<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 nullptr;
}
int main(int argc, const char* argv[])
{
// get the argument
int arg = (argc>1)?std::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
frios::posix::thread worker(calc_fib, &comp);
// wait for the thread to finish
worker.wait_for();
// print the result
std::cout << "fib(" << comp.argument << ") = " << comp.result << std::endl;
return 0;
}