《多核程序设计5(版本2)》由会员分享,可在线阅读,更多相关《多核程序设计5(版本2)(48页珍藏版)》请在金锄头文库上搜索。
1、Chapter 5 Linux Multi-thread Programming李素科北京大学软件与微电子学院2007,2,What is a thread?,A thread is an independent sequence of execution of program code inside a UNIX processA thread is often called a lightweight process but it is NOT a process (something smaller than a process),process space,thread,3,Why T
2、hreads?,Do concurrent control more efficiently Use fork() to create a process:is expensive, usually the child process need copy the whole context from the parent process.Inter-process communication is expensive and difficult.OS does more effort to switch process contexts.Creating a threadThreads use
3、 and exist within the process resources, so creating a thread is faster than creating a process.Inter-thread communication is easy, usually we can use global variable or struct to share data between threads.OS switches thread contexts easier than process contexts.,4,Shared or Not Shared between thre
4、ad and process,Sharedprocess instructionmost data(A thread can have its own private data)open filessignal handlers and signal dispositionscurrent working directoryuser and group IDNot sharedthread IDset of registers (including pc and sp)stacksignal maskpriority,5,What are Pthreads?,IEEE POSIX standa
5、rd p1003.1c (Pthreads) specifies the APIs and the way other POSIX interfaces deal with threadsPthreads are defined as a set of C language programming types and procedure calls i.e. Create a new thread: #include int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(voi
6、d *), void * arg); We want to link a pthread application in Linux , we need libpthread library. so, you can compile file with -lpthread flag # gcc xxxx.c -o xxxx -lpthread,6,Creating Threads,#include int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *(*start_routine)(void *), void *
7、 arg);,thread identifier,thread attributepthread_attr_init() sets the attribute of a thread,point to function,What does the thread do?,Sometime, you need pass some arguments to the thread function,Return value:On success, the identifier of the newly created thread is stored in the location pointed b
8、y the thread argument, and a 0 is returned. On error, a non-zero error code is returned.,7,Waiting For the Termination of Threads,#include int pthread_join(pthread_t th, void *thread_return);pthread_join suspends the execution of the calling thread until the thread identified by th terminatesIf thre
9、ad_return is not NULL, the return value of th is stored in the location pointed to by thread_returnThe joined thread th must be in the joinable state: it must not have been detached using pthread_detach or the PTHREAD_CREATE_DETACHED attribute to pthread_createpthread_join must be called once for ea
10、ch joinable thread created to avoid memory leaks,because memory resources (thread descriptor and stack) of joinable threads are not deallocated if the caller do not call pthread_join.,Waiting for th to terminate,8,Destroying Threads,#include void pthread_exit(void *retval);Ways for threads to termin
11、ate:The thread returns from its starting routine;The thread calls pthread_exit (); The thread is canceled by another thread via pthread_cancel();The thread receives a signal that terminates it;The entire process is terminated.,return value of the thread,can not point to local thread object,9,pthread
12、_detach,#include int pthread_detach(pthread_t th);This guarantees that the memory resources consumed by th will be freed immediately when th terminates.But this prevents other threads from synchronizing on the termination of th using pthread_join.A thread can be created initially in the detached sta
13、te, using the detachstate attribute to pthread_create.After pthread_detach completes, subsequent attempts to perform pthread_join on th will fail.If another thread is already joining the thread th at the time pthread_detach is called, pthread_detach does nothing and leaves th in the joinable state.O
14、n success, 0 is returned. On error, a non-zero error code is returned.,10,pthread_self,#include pthread_t pthread_self(void);return identifier of current thread,11,Mutex-protecting your critical sections,pthread_mutex_t mylock;mylock = PTHREAD_MUTEX_INITIALIZER;pthread_mutex_lock(,A mutex will be ow
15、ned by only one thread at one timeIf another thread call pthread_mutex_lock() on a unlocked mutex, another thread which calls pthread_mutex_lock too is suspended and waits for the owner of locked mutex thread to unlock the mutex first.,12,Avoiding Deadlocks,/* Thread A */pthread_mutex_lock(,/* Threa
16、d B */pthread_mutex_lock(,time,13,Avoiding Deadlocks Cont.,pthread_mutex_lock(,time,pthread_mutex_lock(,14,Operations on Mutexes,#include pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex- attr_t *mutexattr); int pthread_mutex_l
17、ock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); int pthread_mutex_destroy(pthread_mutex_t *mutex);In the LinuxThreads implementation, no resources are associated with mutex objects, thus pthread_mutex_destroy actually does nothing except checking that the mutex is unlocked.,