首页 > 技术文章 > advanced linux programming note

idiotshi 2014-07-17 18:29 原文

CHAPTER 4 THREAD

1.pthread_create function creates thread that share the same memory with the process.

2.pthread_join function wait for threads until they stop

3.The pthread_self function returns the thread ID of the thread in which it iscalled;This thread ID may be compared with another thread ID using the
pthread_equal function

1 if (!pthread_equal (pthread_self (), other_thread))
2     pthread_join (other_thread, NULL);

4.one of thread's important attribute is the detach state,which includes joinable state(default) and detached thread.the difference is that the joinable thread is not automatically cleaned up by GNU/Linux when it terminates,but needs pthread_join to do the clean up.A detached thread is just the opposite.

Even if a thread is created in a joinable state, it may later be turned into a detached thread.To do this, call pthread_detach . Once a thread is detached, it cannot be made joinable again.

5.Unlike process,all threads in a single program share the same address space,however,each thread has its own call stack.BUT,in order to duplicate a certain variable so that each thread has a separate copy,GNU/LINUX supports this by providing each thread with a  thread-specific data aera.The variables stored in this area are duplicated for each thread,and each thread may modify its copy of a variable without affecting other threads.

//define a global variable with type pthread_key_t
static pthread_key_t thread_log_key;

//
void thread_func(void*)
{
    ...
    /*assoctiate the key with this thread,thread_log is the param used in the close_thread_log func*/   
    pthread_setspecific (thread_log_key, thread_log);
    ...       
}

int main()
{
    ...
    /*create a key associate with the thread-specific aera,close_thread_log is the func  called when the thread exit */
    pthread_key_create (&thread_log_key, close_thread_log);
    ....   
}

6.Thread SYNC

- Mutex:if one thread locks a mutex,others need to wait[blocked] until the first thread unlocks the mutex.but we can use pthread_mutex_trylock instead of pthread_mutex_lock to return immediately.

/*
 * set mutex to PTHREAD_MUTEX_ERRORCHECK_NP mode
 * also can be set bo PTHREAD_MUTEX_RECURSIVE_NP mode
 */
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
pthread_mutexattr_init (&attr);
pthread_mutexattr_setkind_np (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init (&mutex, &attr);
pthread_mutexattr_destroy (&attr);


pthread_mutex_lock (&mutex);
//do something
...
pthread_mutex_unlock (&mutex);

 

- semaphore

推荐阅读