線程解析(三)
作者:曹忠明,華清遠見嵌入式學院講師。
前面我們說了線程的創(chuàng)建和撤銷,這里我們說一下線程間的同步的問題。
當同一個進程中存在多個線程的時候,多個線程共享相同的內存,確保每個線程能夠看到一致的數(shù)據(jù)視圖,如果每個線程中都不會讀取或修改共同享有的變量,就不會存在一致性的問題,同樣如果共享變量時只讀的也就不會存在這個問題。但是,當某個線程可一個修改變量,而其他的線程去讀取或修改這個變量的時候,就需要進行線程間的同步,確保他們訪問變量的內容時不會訪問到無效的數(shù)據(jù)。
這里介紹一種實現(xiàn)同步的方法:互斥量
互斥鎖本質上是一把鎖,在訪問共享資源的時候對互斥量進行加鎖,訪問結束后解鎖。在這里我們說一下如何去操作互斥鎖。
1、 創(chuàng)建和撤銷
互斥量用pthread_mutex_t數(shù)據(jù)類型來表示,在使用之前必須對其進行初始化,用完之后釋放內存。互斥量初始化可以用PTHREAD_MUTEX_INITIALIZER來初始化(靜態(tài)初始化),亦可以使用pthread_mutex_init函數(shù)來實現(xiàn),這種方法動態(tài)的為互斥量分配內存,使用后必須使用pthread_mutex_destroy來釋放內存單元。下面是這些函數(shù)的原型:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
2、 鎖操作
鎖操作主要包括加鎖pthread_mutex_lock()、解鎖pthread_mutex_unlock()和測試鎖pthread_mutex_trylock()三個。通過pthread_mutex_lock對互斥量加鎖,這里需要獲得鎖,如果無法獲得鎖則調用線程將阻塞到其他線程調用pthread_mutex_unlock對互斥量解鎖。
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
如果線程不希望被阻塞,則可以調用pthread_mutex_trylock嘗試對互斥量進行加鎖,當互斥量沒有被加鎖,則函數(shù)返回0,并鎖住互斥量,否則會失敗,返回EBUSY.
3、 示例
下面我們用一個例程說明一下這些函數(shù)的使用。
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
void *thread_a(void *arg)
{
printf("thread a entern");
pthread_mutex_lock(&mutex);
printf("mutex lockn");
sleep(10);
pthread_mutex_unlock(&mutex);
printf("mutex unlockn");
}
void *thread_b(void *arg)
{
printf("thread b entern");
while(pthread_mutex_trylock(&mutex))
{
printf("pthread trylockn");
sleep(1);
}
printf("mutex lockn");
pthread_mutex_unlock(&mutex);
printf("mutex unlockn");
}
int main(int argc, char **argv)
{
pthread_t tid_a,tid_b;
int err;
if(pthread_mutex_init(&mutex, NULL) != 0)
{
perror("pthread_mutex_init");
}
err = pthread_create(&tid_a,NULL,thread_a,NULL);
if(err < 0)
{
perror("pthread_create thread_a");
}
sleep(1);
err = pthread_create(&tid_b,NULL,thread_b,NULL);
if(err < 0)
{
perror("pthread_create thread_a");
}
sleep(20);
printf("the main closen");
return 0;
}
結果:
thread a enter
mutex lock
thread b enter
pthread trylock
pthread trylock
pthread trylock
pthread trylock
pthread trylock
pthread trylock
pthread trylock
pthread trylock
pthread trylock
mutex unlock
mutex lock
mutex unlock
the main close
由這里的結果可以看出mutex的用處及幾個相關函數(shù)的使用方法。
“本文由華清遠見http://www.embedu.org/index.htm提供”
來源:華清遠見0次