Monday, February 25, 2013

C++ and pthreads on Linux

If one wants to use NDK and that is JNI on Android, sooner or later he will run into threading on Linux, yes Android is Linux. Pthreads is short for POSIX threads where POSIX is Portable Operating System Interface. Since they are portable they will work on Unix, Linux, FreeBSD, Mac and so on. Pthread is defined in pthread.h and represents set of C functions, structs and defs, to discover where it is you can execute from terminal:

$ locate pthread.h

If you have NDK installed you will see that pthread.h is part of it and that arch-arm version is significantly smaller than /usr/include/pthread.h one. To cut long story short we can do Hello World and see how it looks like:


It is quite simple, we declare thread function, thread itself and then we create thread and pass function pointer and argument in pthread_create. Later we join and exit. To compile it we do:

g++ -pthread simple.cpp -o simple

That -pthread switch is linking instruction. Now cout is not thread safe and we may want to use mutex to make printing to standard output safe.


Now one can go and wrap pthread or mutex in class and make it easier to use. Only we need to be careful with that function pointer in pthread_create, that is C function and passing class method won’t work without some additional coding and static casting.
Finally we will take a look at pthread_key_create, which is recommended by Android documentation. Its signature is:

int pthread_key_create(pthread_key_t *key, void (*destructor)(void *));

That "destructor" should free resources taken by key when thread exits. Key itself is global variable but on thread level, sort of locally global. So here is example:


When you build it and execute it you will see that cout is not thread safe. If you want to wrap pthread in class, very good reading is Implementation and Usage of a Thread Pool based on POSIX Threads by Ronald Kriemann, sorry do not have link for it. Beside mutex, there are are condition variables and semaphores to help with concurrency issues. If you are going to fork process you may want to use System V semaphores instead of pthread semaphores. Finally for any serious implementation of pthread_key_create you need to look at pthread_once_t.

No comments:

Post a Comment