Saturday, August 23, 2008

Linux / Unix Multi-threading - System programming.

Creating Multiple Threads.

1. pthread_create( ): pthread library is being used for achieving multi-threading in Linux/Unix system programming. Always remember to define the flag -D_REENTRANT during cc/gcc compile. It brings in the re-entrant versions of the libraries into linking. Another thing is, You have to include the flag -lpthread during compilation so that the pthread library functions come into affect.

pthread_create has the following params -
a. param 1 - pthread_t thread_id
b. param 2 - pthread_attr_t * attr ( Thread attribute. )
c. param 3 - the start function for the thread.
d. param 4 - a void * which will be passed to the thread start function as a parameter.

2. pthread_join( ) : pthread_join is like wait( ) for processes. By calling pthread_join( ), the caller will wait for the thread created to terminate.

It takes two parameters.
a. thread-id of the thread to which to join.
b. return value from the thread, it's a double pointer.

3. pthread_exit( ) : It terminates the calling thread. It's implicitly called when the start function for a thread finishes.

4. pthread_detach ( ) and pthread_rejoin ( ) : If two threads don't require synchronization, pthread_detach is called and the threads can rejoin by calling pthread_rejoin.

5. Thread attributes - First You have to initialize the attributes and in the end You have to destroy the attribute once You are done. There are lots of things you can do by working with the thread attributes. Like You can alter the scheduling policy, calculation of the scheduling units and lots of other things like create threads in detached state, specifying stack size etc.

6. pthread_cancel ( ) - If one thread has to ask another thread to terminate, then use pthread_cancel ( ). It acts like a signal which terminates the called thread.

No comments: