Termination Four ways for a Pthread to terminate Returns from start_routine Call pthread_exit routine Cancel by another thread through pthread_cancel routine exit call
Example: Hello World Program Requirements Print “Hello World” through standard output Use two threads to finish the task, one should print “Hello”, the other should print “World” Terminate all related threads related after finishing the printing task
Passing parameters to threads The pthread_create() routine permits the programmer to pass one argument to the thread start routine. For cases where multiple arguments must be passed, this limitation is overcome by creating a structure which contains all of the arguments, and then passing a pointer to that structure. All arguments must be passed by reference and cast to (void *).
Joining and detaching threads pthread_join (threadid,status) blocks the calling thread until the specified threadid thread terminates. target thread's termination return status placed in status if specified in the target thread's call to pthread_exit(). A joining thread can match one pthread_join() call. It is a logical error to attempt multiple joins on the same thread. pthread_detach (threadid, status) to explicitly detach a thread pthread_attr_setdetachstate (attr,detachstate) pthread_attr_getdetachstate (attr, detachstate)
Mutex Mutual Exclusion Act as a “lock” to prevent race conditions Typical sequence of use create, initialize lock, unlock destroy Losers in the competition for the mutex variable have to block
Creating & Destroying Type: pthread_mutex_t Initializing Statically ○ pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER Dynamically ○ pthread_mutex_init (mutex, attr) pthread_mutex_attr_t attr specifies protocol for priorities, priority ceiling, and process sharing Destroying pthread_mutex_destroy – to delete a mutex object pthread_mutex_attr_destroy – to delete a mutex attr object
Lock & Unlock Lock pthread_mutex_lock (mutex) ○ blocks calling thread if mutex already locked pthread_mutex_trylock(mutex) ○ returns with “busy” code if already locked Unlock pthread_mutex_unlock (mutex) Error ○ mutex is released ○ mutex owned by others
Your consent to our cookies if you continue to use this website.