Thursday, February 07, 2008

POSIX threads in Linux

"POSIX threads" technically means the thread API specified by the inernational formal standard POSIX.

Each thread sees the same global data and files; however,each thread has its own stack and registers (so that variables in the automatic and register storage classes are private).

Anything that you can do with the threads, you can also do with processes sharing memory.
A process is a heavy-weight, kernel-level entity and includes such things as a virtual memory map, file descriptors, user ID, etc, and each process has its own collection of these. The only way for your program to access data in the process structure, to query or change its state, s via s system call.
A thread is a light-weight entity, comprising the registers, stack, and some other data.
All threads in a process share the state of that process. They reside in the exact same memory space, see the same functions, see the same data. When one thread alters a process variable, all the others will see the change when they next access it.
Example: process are like banks in the town, it is hard to change the number of banks. Threads are like a employee working in the bank, he can deal with checking account, loan, "bank stuff", etc. The other employee can also access and share "bank stuff". All employees can work at the same time. [update 2/24/2010]

#include <pthread.h>
#include <string.h> /* for strerror() */
#include <stdio.h>
#define NTHREADS 4

#define errexit(code,str) \
fprintf(stderr,"%s: %s\n",(str),strerror(code)); \

/******** this is the thread code */
void *hola(void * arg)
int myid=*(int *) arg;
printf("Hello, world, I'm %d\n",myid);
return arg;

/******** this is the main thread's code */
int main(int argc,char *argv[])
int worker;
pthread_t threads[NTHREADS]; /* holds thread info */
int ids[NTHREADS]; /* holds thread args */
int errcode; /* holds pthread error code */
int *status; /* holds return code */

/* create the threads */
for (worker=0; worker<NTHREADS; worker++) {
if (errcode=pthread_create(&threads[worker],/* thread struct*/
NULL, /* default thread attributes */
hola, /* start routine */
&ids[worker])) { /* arg to routine*/
/* reap the threads as they exit */
for (worker=0; worker<NTHREADS; worker++) {
/* wait for thread to terminate */
if (errcode=pthread_join(threads[worker],(void *) &status)) {
/* check thread's exit status and release its resources */
if (*status != worker) {
fprintf(stderr,"thread %d terminated abnormally\n",worker);

cc -o simple simple.c -lpthread

It will create NTHREADS threads, each of which starts executing the function hola(). The main thread waits for each of the worker threads to terminate by calling pthread_join() for each thread. Meanwhile, each of the worker threads prints a message and its thread ID and then exits. Once the main thread has reaped all of the workers, the main program exits.

No comments:

Post a Comment