PThreads

From ImageWiki

(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
-
This gives a quick overview of the Posix Threads Library (pthreads):
+
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.
-
[http://yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html http://yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html]
+
#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 falgs.
 +
 
 +
A simple tutorial on PThreads can be found at [http://yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html http://yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html].

Revision as of 09:11, 25 September 2006

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 falgs.

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

Personal tools