執行緒間的互斥的同步一直是乙個很重要的地方,在這裡做個總結
所用的介面
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
void pthread_exit(void *retval);
int pthread_join(pthread_t thread, void **retval);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_cond_wait(pthread_cond_t * cond, pthread_mutex_t * mutex);
int pthread_cond_broadcast (pthread_cond_t *cond) ;
int pthread_cond_signal (pthread_cond_t *cond) ;
練習題:三個執行緒按照順序列印 『a』 『b』 『c』
#include
#include
#include
#include
#include
#include
#define pthead_count 3
char my_wait_flag = 'a';
int flag = 0;
pthread_mutex_t mutex_baiyu = pthread_mutex_initializer;
pthread_cond_t cond_baiyu=pthread_cond_initializer;
void *pthread1(void *argv)
pthread_exit(null);
}int main()
; for (i = 0; i < pthead_count; i++)
for (i = 0; i < pthead_count; i++)
printf("parent exit\n");
return
0;}
makefile內容:
target=pthr
cc=gcc
rm=rm
cflag=-o
lflag= -lpthread -w
src = $(shell ls
*.c)
put = $(patsubst %.c,%.o,$(src))
$(target):$(put)
$(cc) $(cflag) $@
$(src) $(lflag)
clean:
$(rm) -rf $(target) *.o
make之後執行的log:
get thread_140014711187200 param:a
get thread_140014702794496 param:b
get thread_140014694401792 param:c
get thread_140014711187200 param:a
get thread_140014702794496 param:b
get thread_140014694401792 param:c
get thread_140014711187200 param:a
get thread_140014702794496 param:b
get thread_140014694401792 param:c
多執行緒程式設計 互斥鎖 條件變數
一,互斥鎖 在多工作業系統中,有很多任務同時執行,這些任務可能會用到同乙個資源,如果沒有一種機制來控制這些任務共享同乙個資源,那這些任務可能無法正常使用自己想用的資源。互斥鎖 是多工作業系統中一種簡單的加鎖方法,來控制各任務對共享資源的訪問。互斥鎖的狀態 上鎖 lock 和解鎖 unlock 互斥鎖...
多執行緒同步問題(1)互斥鎖和條件變數
最近一段時間學習了很多關於多執行緒的東西,同時專案中也多是此類東西,因此記錄一下 1.多執行緒的問題在於同步,主要是各個執行緒的時間片分配,不能總是給乙個執行緒cpu時間,讓其他執行緒沒有cpu可用 2.多執行緒同步有很多種方法,目前工作中用到的多是互斥鎖,讀寫鎖,條件變數等。3.各種方法的解釋 互...
linux 多執行緒程式設計 互斥鎖與條件變數
條件變數是利用執行緒間共享的全域性變數進行同步的一種機制,主要包括兩個動作 乙個執行緒等待 條件變數的條件成立 而掛起,另乙個執行緒使 條件成立 給出條件成立訊號 為了防止競爭,條件變數的使用總是和乙個互斥鎖結合在一起。下面這個例子展示的是互斥鎖和條件變數的結合使用,以及取消對於條件等待動作的影響,...