linux多執行緒學習 六 訊號量實現同步

2021-07-22 16:05:38 字數 2986 閱讀 9089

訊號量的互斥同步都是通過pv原語來操作的,我們可以通過註冊兩個訊號量,讓它們在互斥的問題上互動,從而達到同步。通過下面例項就可以很容易理解:

[cpp]view plain

copy

#include 

#include 

#include 

#include 

#include 

#include 

#define  return_if_fail(p)  if((p) == 0)    

typedef

struct

_privinfo      

privinfo;      

static

void

info_init (privinfo* thiz);      

static

void

info_destroy (privinfo* thiz);      

static

void

* pthread_func_1 (privinfo* thiz);      

static

void

* pthread_func_2 (privinfo* thiz);      

intmain (

intargc, 

char

** argv)      

info_init (thiz);      

ret = pthread_create (&pt_1, null, (void

*)pthread_func_1, thiz);      

if(ret != 0)      

ret = pthread_create (&pt_2, null, (void

*)pthread_func_2, thiz);      

if(ret != 0)      

pthread_join (pt_1, null);      

pthread_join (pt_2, null);      

info_destroy (thiz);      

return

0;      

}      

static

void

info_init (privinfo* thiz)      

static

void

info_destroy (privinfo* thiz)      

static

void

* pthread_func_1 (privinfo* thiz)      

return

;      

}      

static

void

* pthread_func_2 (privinfo* thiz)      

return

;      

}      

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

pthread2: pthread2 get the unlock.

pthread2: pthread2 unlock.

pthread1: pthread1 get the lock.

pthread1: pthread1 unlock

多執行緒 訊號量

訊號量 semaphore類 建立帶指定許可數的訊號量 semaphore semaphore new semaphore 1 建立乙個許可的訊號量 訊號量用來限制訪問共享數資源的執行緒數。在訪問資源之前,執行緒必須從訊號量獲取許可,在訪問完資源後釋放訊號量。任務通過呼叫訊號量的acquire 方法...

Linux多執行緒同步 訊號量

同步主線程與子執行緒 子執行緒之間的同步 使用單個訊號量 include include include include include include void ret result thread1 void ret result thread2 sem t sem void thread1fun...

Linux 多執行緒訊號量同步

p操作 v操作 include sem t sem 定義訊號量 sem init 初始化訊號量 sem wait 獲取訊號量,訊號量的數值 1 訪問共享資源 sem post 釋放乙個訊號量,及訊號量的數值 1 sem destroy 如果不再使用訊號量,則銷毀訊號量函式和posix ipc的訊號量...