目錄
12、POSIX線程同步技術
1、線程同步
- 兩個(或多個)線程同時執行時,經常需要訪問到公共資源或代碼的關鍵部分,這時就涉及到了線程的同步問題,我們可以通過下面兩種方法來更好地控制線程的執行情況和更好地訪問代碼的關鍵部分
- 信號量
- 互斥量
用信號量進行同步
-
"信號量"的作用就象是代碼周圍的門衛
-
二進制信號量:一種最簡單的一種信號量,只有 0 , 1 兩種取值
-
計數信號量:有更大的取值範圍,一般用於希望有限個線程去執行一段給定的代碼
信號量函數
- 頭文件 <semaphore.h>
- 信號量函數的名字都以"sem_"打頭
- 信號量對象用sem_t表示
2、sem_init函數創建一個信號量
- 作用:對給定的信號量對象進行初始化
int sem_init(sem_t *sem,int pshared,unsigned value);
- 參數
- sem: 要進行初始化的信號量對象
- pshared:控制着信號量的類型,如果值爲0,表示它是當前進程的局部信號量;否則,其他進程就能夠共享這個信號量
- value:賦給信號量對象的一個整數類型的初始值
- 返回:成功返回 0;
3、sem_post函數
- 作用:給信號量的值加上一個"1"
int sem_post(sem_t *sem);
- 參數
- sem: 初始化的信號量對象的指針作爲參數,用來改變該對象的值
- 返回值
- 成功:返回 0;
是一個"原子操作"( 不會被線程調度機制打斷的操作 )-即同時對同一個信號量做加"1"操作的兩個線程是不會衝突的。信號量的值永遠會正確地加上一個"2",因爲有兩個線程試圖改變它
4、sem_wait函數
- 作用:從信號量的值減去一個"1",但它永遠會先等待該信號量爲一個非零值纔開始做減法
int sem_wait(sem_t *sem);
- 參數
- sem: 初始化的信號量對象的指針作爲參數,用來改變該對象的值
- 返回值:成功,0
也是一個"原子操作"
5、sem_destroy函數
- 作用:用完信號量後,對該信號量進行清理
int sem_destroy(sem_t *sem);
- 參數
- sem: 初始化的信號量對象的指針作爲參數,用來改變該對象的值
- 返回值:成功,0
歸還自己佔有的一切資源,在清理信號量的時候如果還有線程在等待它,用戶就會收到一個錯誤
6、信號量實現生產者消費者模型
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM 5
int queue[NUM]; //定義全局變量實現環形隊列
sem_t blank_number, product_number;//空格信號量,產品信號量
void *producer(void *arg)
{
int p = 0;
while (1)
{
sem_wait(&blank_number); //生產者將空格數--,爲0則阻塞等待
queue[p] = rand() % 1000 + 1; //生產一個產品
printf("Produce %d\n", queue[p]);
sem_post(&product_number); //將產品數++
p = (p+1)%NUM;
sleep(rand()%5);
}
return NULL;
}
void *consumer(void *arg)
{
int c = 0;
while (1)
{
sem_wait(&product_number); //消費者將產品數--
printf("Consume %d\n", queue[c]);
queue[c] = 0; //消費一個產品
sem_post(&blank_number); //空格數++,消費掉
c = (c+1)%NUM;
sleep(rand()%5);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
sem_init(&blank_number, 0, NUM);//初始化空格信號量爲5
sem_init(&product_number, 0, 0);//產品數爲0
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&blank_number);
sem_destroy(&product_number);
return 0;
}
7、用互斥量進行同步
- 使用互斥量是實現多線程程序中的同步訪問的另一種手段
- 程序員給某個對象加上一把“鎖”,每次只允許一個線程去訪問它
- 如果想對代碼關鍵部分的訪問進行控制,你必須在進入這段代碼之前鎖定一把互斥量,在完成操作後再打開它
互斥量函數組
#include <pthread.h>
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);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
示例
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
int counter; /* incremented by threads */
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void *doit(void *);
int main(int argc, char **argv)
{
pthread_t tidA, tidB;
pthread_create(&tidA, NULL, &doit, NULL);
pthread_create(&tidB, NULL, &doit, NULL);
/* wait for both threads to terminate */
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
return 0;
}
void *doit(void *vptr)
{
int i, val;
for (i = 0; i < NLOOP; i++) {
//pthread_mutex_lock(&counter_mutex);
val = counter;
val++;
printf("%x: %d\n", (unsigned int)pthread_self(), val);
counter = val;
//pthread_mutex_unlock(&counter_mutex);
}
return NULL;
}
8、條件變量
- 條件變量用來自動阻塞一個線程,直到某特殊情況發生爲止。通常條件下變量和互斥鎖同時使用。
- 條件變量是用來等待事件。
//初始化條件變量
int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr);
//自動釋放mutex鎖,等待條件滿足
int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);
//自動釋放mutex鎖,等待條件滿足,如果在abstime時間內還沒有滿足,則返回錯誤
int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);
//銷燬條件變量
int pthread_cond_destroy(pthread_cond_t *cond);
//讓等待條件滿足的線程中某一個被喚醒
int pthread_cond_signal(pthread_cond_t *cond);
//讓等待條件滿足的線程中全部被喚醒
int pthread_cond_broadcast(pthread_cond_t *cond);
9、條件變量加互斥鎖實現生產者消費者模型
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#define ERR_EXIT(m) do { perror(m);exit(EXIT_FAILURE); } while(0)
int nready=0;
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
pthread_t tid[10];
void *produce(void *data)
{
int i;
long n=(long)data;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&g_mutex);
nready++;
printf("%ld produce nready=%d\n",n,nready);
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_mutex);
sleep(4);
}
return NULL;
}
void *cust(void *data)
{
int i;
long n=(long)data;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&g_mutex);
while(nready<=0)
{
printf("%ld cust wait for a cond\n",n);
sleep(1);
pthread_cond_wait(&g_cond,&g_mutex);
}
--nready;
printf("%ld cust nready=%d\n",n,nready);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
int main(int argc,char *argv[])
{
pthread_mutex_init(&g_mutex,NULL);
pthread_cond_init(&g_cond,NULL);
int i;
for(i=0;i<5;i++)
pthread_create(&tid[i],NULL,produce,(void *)&i);
for(i=0;i<5;i++)
pthread_create(&tid[i+5],NULL,cust,(void *)&i);
for(i=0;i<10;i++)
pthread_join(tid[i],NULL);
pthread_cond_destroy(&g_cond);
pthread_mutex_destroy(&g_mutex);
return 0;
}
10、信號量、互斥量、條件變量封裝
//locker.h
#ifndef LOCKER_H
#define LOCKER_H
#include <exception>//異常處理
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <cstdlib>
/*封裝信號量的類*/
class Sem
{
public:
Sem()
{
if(sem_init(&m_sem,0,0) != 0){
std::cout<<"Error:sem_init"<<std::endl;
exit(1);
}
}
~Sem()
{
sem_destroy(&m_sem);
}
bool wait()
{
return sem_wait(&m_sem) == 0;
}
bool post()
{
return sem_post(&m_sem) == 0;
}
private:
sem_t m_sem;
};
/*封裝互斥鎖的類*/
class Locker
{
public:
Locker()
{
if(pthread_mutex_init(&m_mutex,NULL) != 0){
std::cout<<"Error:pthread_mutex_init"<<std::endl;
exit(1);
}
}
~Locker()
{
pthread_mutex_destroy(&m_mutex);
}
bool lock()
{
return pthread_mutex_lock(&m_mutex) == 0;
}
bool unlock()
{
return pthread_mutex_unlock(&m_mutex) == 0;
}
private:
pthread_mutex_t m_mutex;
};
/*封裝條件變量*/
class Cond
{
public:
Cond()
{
if(pthread_mutex_init(&m_mutex,NULL) != 0){
std::cout<<"Error:pthread_mutex_init"<<std::endl;
exit(1);
}
if(pthread_cond_init(&m_cond,NULL) != 0){
pthread_mutex_destroy(&m_mutex);
std::cout<<"Error:pthread_cond_init"<<std::endl;
exit(1);
}
}
~Cond()
{
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_cond);
}
bool wait()
{
int ret = 0;
pthread_mutex_lock(&m_mutex);
ret = pthread_cond_wait(&m_cond,&m_mutex);
pthread_mutex_unlock(&m_mutex);
return ret == 0;
}
bool signal()
{
return pthread_cond_signal(&m_cond) == 0;
}
private:
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;
};
#endif