PThreads

From ImageWiki

Jump to: navigation, search

The following simple program illustrates the basics of the POSIX Threads library (pthreads). The program doesn't really do anything except starting a thread that runs forever.

#include <pthread.h>

pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;

void* some_thread(void *arg)
{
    while (true) {
        pthread_mutex_lock(&my_mutex);
        // Do something
        pthread_mutex_unlock(&my_mutex);
    }
}

int main(int argc, char *argv[]) 
{
    pthread_t thread;
    pthread_create(&thread, NULL, some_thread, NULL);

    // Do something (possibly join the thread)

    return 0;
}

When you need to link to PThreads on GNU/Linux, simply add -lpthread to your link flags.

Contents

On mutexes

Mutexes (as you should know, given your acquired knowledge on multiprogramming!) are used for synchronisation of threads and/or when you want to make sure that multiple threads don't mess with the same data store. In general you should use as few mutexes, and other semaphors, as possible as they introduce dependecies among the threads - contrary to what you are trying to achieve by using multiple threads.

If you only have one thread writing to a data store, it shouldn't be necessary to introduce semaphors, except if it's a complex data store, such as a data object, which can be left in an inconsistent state.

Efficiency

To make a thread release the processor for use of other threads, add the call

pthread_yield();

where you want to release the thread.

Further information

A simple tutorial on PThreads can be found at http://yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html.

Notes

Note: At some point, we need a better tutorial on this wiki.

Personal tools