本文可任意轉載,但必須註明作者和出處。
【原創】手把手教你Linux下的多線程設計(四)
--Linux下多線程編程詳解
原創作者:Frozen_socker(冰棍)
E_mail:dlskyfly@163.com
線程同步
首先來看一下有關同步機制的概念。同步就是若干個線程等待某個事件的發生,當等待事件發生時,一起開始繼續執行。可以這樣簡單理解同步,就是若干個線程各自對自己的資料進行處理,然後在某個點必須匯總一下資料,否則不能進行下一步的處理工作。 線程同步的函數調用有pthread_cond_init、pthread_cond_broadcast、pthread_cond_signal、pthread_cond_wait和pthread_cond_destroy
函數原型:int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
函數說明:
按attr指定的屬性初始化cond條件變數。如果attr為NULL,效果等同於pthread_cond_t cond = PTHREAD_COND_INITIALIZER
函數原型:
int pthread_cond_broadcast(pthread_cond_t *cond);
函數說明:
對所有等待cond這個條件變數的線程解除阻塞。
函數原型:
int pthread_cond_signal(pthread_cond_t *cond);
函數說明:
僅僅解除等待cond這個條件變數的某一個線程的阻塞狀態。如果有若干線程掛起等待該條件變數,該調用只喚起一個線程,被喚起的線程是哪一個是不確定的。
函數原型:
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
函數說明:
該調用自動阻塞發出調用的當前線程,並等待由參數cond指定的條件變數,而且為參數mutex指定的互斥體解鎖。被阻塞線程直到有其他線程調用pthread_cond_signal或pthread_cond_broadcast函數置相應的條件變數時,而且獲得mutex互斥體才解除阻塞。等待狀態下的線程不佔用CPU時間。
函數原型:
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
函數說明:
該函數自動阻塞當前線程等待參數cond指定的條件變數,並為參數mutex指定的互斥體解鎖。被阻塞的線程被喚起繼續執行的條件是:有其他線程對條件變數cond調用pthread_cond_signal函數;或有其他線程對條件變數cond調用pthread_cond_broadcast;或系統時間到達abstime參數指定的時間;除了前面三個條件中要有一個被滿足外,還要求該線程獲得參數mutex指定的互斥體。
函數原型:
int pthread_cond_destroy(pthread_cond_t *cond);
函數說明:
釋放cond條件變數佔用的資源。
看下面的樣本:
//example_5.c
#include <stdio.h>
#include <pthread.h>
pthread_t pt1,pt2;
pthread_mutex_t mu;
pthread_cond_t cond;
int i = 1;
void * decrease(void * arg)
...{
while(1)
...{
pthread_mutex_lock(&mu);
if(++i)
...{
printf("%d ",i);
if(i != 1) printf("Error ");
pthread_cond_broadcast(&cond);
pthread_cond_wait(&cond,&mu);
}
sleep(1);
pthread_mutex_unlock(&mu);
}
}
void * increase(void * arg)
...{
while(1)
...{
pthread_mutex_lock(&mu);
if(i--)
...{
printf("%d ",i);
if(i != 0) printf("Error ");
pthread_cond_broadcast(&cond);
pthread_cond_wait(&cond,&mu);
}
sleep(1);
pthread_mutex_unlock(&mu);
}
}
int main()
...{
pthread_create(&pt2,NULL,increase,NULL);
pthread_create(&pt1,NULL,decrease,NULL);
pthread_join(pt1,NULL);
pthread_join(pt2,NULL);
}
以上我們講解過了Linux下利用pthread.h標頭檔的多線程編程知識,下一章中,我們繼續講解關於多線程的深入編程知識,敬請期待。