Appendix 2: Linux Multithreading Programming
Thread
Thread likes process, but it may have less cost. All threads created in a process shares the common resources (such as global variables), this may make it tricky to program and debug multithreading programs.
Thread Basics
#include <pthread.h>
// create
int pthread_create(pthread_t* pThread,
pthread_attr_t* pThreadAttr,
void* (*pThreadFunc)(void*),
void* arg);
// called in thread func on exit to return a value
void pthread_exit(void* pThreadReturnValue);
// called in a thread to get return value of another thread when it exits
int pthread_join(pthread_t thread, void** ppThreadReturnValue);
// attributes
pthread_attr_t threadAttr; // define attr variable
int pthread_attr_init(pthread_attr_t* pThreadAttr);
int pthread_attr_setdetachstate(pthread_attr_t* pThreadAttr, int state);
state: PTHREAD_CREATE_JOIN - can be joined when exit
PTHREAD_CREATE_DETACHED - just exit by itself
...
// cancel/stop a thread from another thread
int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int* oldState);
state/oldstate: PTHREAD_CANCEL_ENABLE,
PTHREAD_CANCEL_DISABLE
int pthread_setcanceltype(int type, int* oldType);
type/oldType: PTHREAD_CANCEL_ASYNCHRONOUS - start exiting at once when get cancel request
PTHREAD_CANCEL_DEFERRED - first do something else.
Synchronization
Semaphore
#include <semaphore.h>
sem_t semaphore; // define a semaphore
// create semaphore
int sem_init(sem_t* pSemaphore, int shared, unsigned int uInitialValue);
// add 1 to semaphore value. atomic operation
int sem_post(sem_t* pSemaphore);
// minus 1 to semaphore value. atomic operation.
// if semaphore value is 0, then wait and block
int sem_wait(sem_t* pSemaphore);
// destroy and clean up
int sem_destroy(sem_t* pSemaphore);
Mutex
#include <pthread.h>
pthread_mutex_t mutex; // define a mutex
// create
int pthread_mutex_init(pthread_mutex_t* pMutex, const pthread_mutexattr_t* pMutexAttr);
// lock it
int pthread_mutex_lock(pthread_mutex_t* pMutex);
// unlock it
int pthread_mutex_unlock(pthread_mutex_t* pMutex);
// destroy
int pthread_mutex_destroy(pthread_mutex_t* pMutex);
Exception Handling
The C++ exception handling mechanism (try, catch, throw) offers the proper infrastructure for handling exceptions locally. Each thread has its own exception handling stack, which operates almost independently. Exceptions are never thrown between threads.