執行緒同步(互斥量)

2021-08-18 07:26:48 字數 2068 閱讀 4699

原理:

建立與銷毀:

#include 

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);

int pthread_mutex_destroy(pthread_mutex_t *mutex);

//兩個函式的返回值:若成功,返回0;否則,返回錯誤編碼

//要用預設的屬性初始化互斥量,只需把attr設為 null。

加鎖與解鎖

對互斥量進行加鎖,需要呼叫pthread_mutex_lock。如果互斥量已經上鎖,呼叫執行緒將阻塞直到互斥量被解鎖。

對互斥量解鎖,需要呼叫pthread_mutex_unlock。

#include 

int pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex);

int pthread_mutex_unlock(pthread_mutex_t *mutex);

//所有函式的返回值:若成功,返回0;否則,返回錯誤編碼。

如果執行緒不希望被阻塞,它可以使用pthread_mutex_trylock嘗試對互斥量進行加鎖。

如果呼叫pthread_mutex_trylock時,互斥量處於未鎖住狀態,那麼pthread_mutex_trylock將鎖住互斥量,不會出現阻塞,直接返回0。

如果互斥量已經被鎖住了,pthread_mutex_trylock就會失敗,不能鎖住互斥量,不阻塞,直接返回ebusy。

例項:

#include 

#include

struct foo;

struct foo *foo_alloc(int id) /* 申請並分配物件空間 */

/* ... continue initialization ...*/

}return (fp);

}void foo_hold(struct foo *fp) /* 對物件增加了乙個引用 */

void foo_rele(struct foo *fp)/* 釋放引用物件 */

else

}

死鎖

避免死鎖

假設需要對兩個互斥量a和b同時加鎖。如果所有的執行緒總是在對互斥量b加鎖之前鎖住互斥量a,那麼使用這兩個互斥量就不會產生死鎖(當然,在其他的資源上仍可能出現死鎖)。

如果已經占有某些鎖 而且pthread_mutex_trylock介面返回成功,那麼就可以前進。但是,如果不能 獲取鎖, 可以先釋放已經占有的鎖, 做好清理工作, 然後過一段時間再重新嘗試獲取。

具有超時的加鎖方式

pthread_mutex_timedlock函式與pthread_mutex_lock是基本等價的,但是在達到超時時間值 時,pthread_mutex_timedlock不會對互斥量進行加鎖,而是返回錯誤碼 etimedout。

#include < pthread. h>

#include < time. h>

int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex, const

struct timespec *restrict tsptr);

//返回值:若成功,返回0;否則,返回錯誤編碼。

注意:

超時是指定願意等待的絕對時間(與相對時間對比而言,指定在時間x之前可以阻塞等待,而不是說願意阻塞 y秒)。這個超時時間是用timespec結構來表示的,它用秒和納秒來描述時間。

例項

#include 

#include

#include

int main()else

}

注意:

mac os 10.12.6還不支援pthread_mutex_timelock函式,但是linux 3.2.0、freebsd 8.0以及solaris 10支援該函式。

執行緒同步 互斥量

下面以乙個簡單的多執行緒程式來演示如何使用互斥量來進行執行緒同步。在主線程中,我們建立子執行緒,並把陣列msg作為引數傳遞給子執行緒,然後主線程呼叫函式pthread mutex lock對互斥量加鎖,等待輸入,輸入完成後,呼叫函式pthread mutex unlock對互斥量解鎖,從而使執行緒函...

執行緒同步 互斥量

互斥量的使用 執行緒同步之互斥量 include include include include include include include using namespace std 全域性變數,兩個執行緒都可以修改,因此修改的時候需要加鎖 int g value 0 互斥量 pthread mu...

執行緒同步 使用互斥量

1.初始化與銷毀互斥量 linux使用pthread mutex t 資料型別表示互斥量,並使用pthread mutex init函式對互斥量進行初始化。include int pthread mutex init pthread mutex t restrict mutex,const pthr...