Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
Posix信號(hào)量
Posix?信號(hào)量 | |
有名信號(hào)量 | 無(wú)名信號(hào)量 |
sem_open | sem_init |
sem_close | sem_destroy |
sem_unlink | ? |
sem_wait | |
sem_post | |
?
有名信號(hào)量
#include <fcntl.h> /* For O_* constants */ #include <sys/stat.h> /* For mode constants */ #include <semaphore.h> sem_t *sem_open(const char *name, int oflag); sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value); int sem_close(sem_t *sem); int sem_unlink(const char *name);??與Posix類IPC用法類似:?名字以/somename形式標(biāo)識(shí),且只能有一個(gè)/?,并且總長(zhǎng)不能超過(guò)NAME_MAX-4?(i.e.,?251)。
??Posix有名信號(hào)量需要用sem_open?函數(shù)創(chuàng)建或打開(kāi),PV操作分別是sem_wait?和?sem_post,可以使用sem_close?關(guān)閉,刪除用sem_unlink。
??有名信號(hào)量用于不需要共享內(nèi)存的進(jìn)程間同步(可以通過(guò)名字訪問(wèn)),?類似System?V?信號(hào)量。
?
匿名信號(hào)量
#include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); int sem_destroy(sem_t *sem);??匿名信號(hào)量只存在于內(nèi)存中,?并要求使用信號(hào)量的進(jìn)程必須可以訪問(wèn)內(nèi)存;?這意味著他們只能應(yīng)用在同一進(jìn)程中的線程,?或者不同進(jìn)程中已經(jīng)映射相同內(nèi)存內(nèi)容到它們的地址空間中的線程.
??匿名信號(hào)量必須用sem_init?初始化,sem_init?函數(shù)的第二個(gè)參數(shù)pshared決定了線程共享(pshared=0)還是進(jìn)程共享(pshared!=0),也可以用sem_post?和sem_wait?進(jìn)行操作,在共享內(nèi)存釋放前,匿名信號(hào)量要先用sem_destroy?銷毀。
?
Posix信號(hào)量PV操作
int sem_wait(sem_t *sem); //P操作 int sem_post(sem_t *sem); //V操作??wait操作實(shí)現(xiàn)對(duì)信號(hào)量的減1,?如果信號(hào)量計(jì)數(shù)原先為0則會(huì)發(fā)生阻塞;
??post操作將信號(hào)量加1,?在調(diào)用sem_post時(shí),?如果在調(diào)用sem_wait中發(fā)生了進(jìn)程阻塞,?那么進(jìn)程會(huì)被喚醒并且sem_post增1的信號(hào)量計(jì)數(shù)會(huì)再次被sem_wait減1;
?
Posix互斥鎖
#include <pthread.h> int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); //互斥鎖初始化, 注意:函數(shù)成功執(zhí)行后,互斥鎖被初始化為未鎖住狀態(tài)。 int pthread_mutex_lock(pthread_mutex_t *mutex); //互斥鎖上鎖 int pthread_mutex_trylock(pthread_mutex_t *mutex); //互斥鎖判斷上鎖 int pthread_mutex_unlock(pthread_mutex_t *mutex); //互斥鎖解鎖 int pthread_mutex_destroy(pthread_mutex_t *mutex); //消除互斥鎖??互斥鎖是用一種簡(jiǎn)單的加鎖方法來(lái)控制對(duì)共享資源的原子操作。這個(gè)互斥鎖只有兩種狀態(tài),也就是上鎖/解鎖,可以把互斥鎖看作某種意義上的全局變量。在同一時(shí)刻只能有一個(gè)線程掌握某個(gè)互斥鎖,擁有上鎖狀態(tài)的線程能夠?qū)蚕碣Y源進(jìn)行操作。若其他線程希望上鎖一個(gè)已經(jīng)被上鎖的互斥鎖,則該線程就會(huì)阻塞,直到上鎖的線程釋放掉互斥鎖為止。可以說(shuō),這把互斥鎖保證讓每個(gè)線程對(duì)共享資源按順序進(jìn)行原子操作。
??其中,互斥鎖可以分為快速互斥鎖(默認(rèn)互斥鎖)、遞歸互斥鎖和檢錯(cuò)互斥鎖。這三種鎖的區(qū)別主要在于其他未占有互斥鎖的線程在希望得到互斥鎖時(shí)是否需要阻塞等待。快速鎖是指調(diào)用線程會(huì)阻塞直至擁有互斥鎖的線程解鎖為止。遞歸互斥鎖能夠成功地返回,并且增加調(diào)用線程在互斥上加鎖的次數(shù),而檢錯(cuò)互斥鎖則為快速互斥鎖的非阻塞版本,它會(huì)立即返回并返回一個(gè)錯(cuò)誤信息。?
?
生產(chǎn)者消費(fèi)者問(wèn)題
運(yùn)用C++,?將緩沖區(qū)封裝成class?Storage
//Storage類設(shè)計(jì) class Storage { public:Storage(unsigned int _bufferSize);~Storage();void consume(int id); //消費(fèi)void produce(int id); //生產(chǎn)private:// 打印緩沖區(qū)狀態(tài)void display(bool isConsumer = false);private:unsigned int buffSize;int *m_storage; //緩沖區(qū)unsigned short int in; //生產(chǎn)位置unsigned short int out; //消費(fèi)位置unsigned int product_number; //產(chǎn)品編號(hào)sem_t sem_full; //滿信號(hào)量sem_t sem_empty;//空信號(hào)量pthread_mutex_t mutex; //互斥量: 保護(hù)緩沖區(qū)互斥訪問(wèn) }; //Storage類實(shí)現(xiàn) Storage::Storage(unsigned int _bufferSize):buffSize(_bufferSize), in(0), out(0), product_number(0) {m_storage = new int[buffSize];for (unsigned int i = 0; i < buffSize; ++ i)m_storage[i] = -1;sem_init(&sem_full, 0, 0);//將empty信號(hào)量初始化為緩沖區(qū)大小sem_init(&sem_empty, 0, buffSize);pthread_mutex_init(&mutex, NULL); }Storage::~Storage() {delete []m_storage;pthread_mutex_destroy(&mutex);sem_destroy(&sem_empty);sem_destroy(&sem_full); } void Storage::produce(int id) {printf("producer %d is waiting storage not full\n", id);//獲取empty信號(hào)量sem_wait(&sem_empty);//獲取互斥量pthread_mutex_lock(&mutex);//生產(chǎn)cout << "++ producer " << id << " begin produce "<< ++product_number << " ..." << endl;m_storage[in] = product_number;//打印此時(shí)緩沖區(qū)狀態(tài)display(false);in = (in+1)%buffSize;cout << " producer " << id << " end produce ...\n" << endl;//釋放互斥量pthread_mutex_unlock(&mutex);//釋放full信號(hào)量sem_post(&sem_full);sleep(1); } void Storage::consume(int id) {printf("consumer %d is waiting storage not empty\n", id);//獲取full信號(hào)量sem_wait(&sem_full);//獲取互斥量pthread_mutex_lock(&mutex);//消費(fèi)int consume_id = m_storage[out];cout << "-- consumer " << id << " begin consume "<< consume_id << " ..." << endl;m_storage[out] = -1;//打印此時(shí)緩沖區(qū)狀態(tài)display(true);out = (out+1)%buffSize;cout << " consumer " << id << " end consume ...\n" << endl;//解鎖互斥量pthread_mutex_unlock(&mutex);//釋放empty信號(hào)量sem_post(&sem_empty);sleep(1); } void Storage::display(bool isConsme) {cout << "states: { ";for (unsigned int i = 0; i < buffSize; ++i){if (isConsme && out == i)cout << '#';else if (!isConsme && in == i)cout << '*';if (m_storage[i] == -1)cout << "null ";elseprintf("%-4d ", m_storage[i]);}cout << "}" << endl; } //生產(chǎn)者, 消費(fèi)者代碼實(shí)現(xiàn) //緩沖區(qū) Storage *storage; //生產(chǎn)者-線程 void *producer(void *args) {int id = *(int *)args;delete (int *)args;while (1)storage->produce(id); //生產(chǎn)return NULL; } //消費(fèi)者-線程 void *consumer(void *args) {int id = *(int *)args;delete (int *)args;while (1)storage->consume(id); //消費(fèi)return NULL; } //主控線程 int main() {int nProducer = 1;int nConsumer = 2;cout << "please input the number of producer: ";cin >> nProducer;cout << "please input the number of consumer: ";cin >> nConsumer;cout << "please input the size of buffer: ";int size;cin >> size;storage = new Storage(size);pthread_t *thread = new pthread_t[nProducer+nConsumer];//創(chuàng)建消費(fèi)者進(jìn)程for (int i = 0; i < nConsumer; ++i)pthread_create(&thread[i], NULL, consumer, new int(i));//創(chuàng)建生產(chǎn)者進(jìn)程for (int i = 0; i < nProducer; ++i)pthread_create(&thread[nConsumer+i], NULL, producer, new int(i));//等待線程結(jié)束for (int i = 0; i < nProducer+nConsumer; ++i)pthread_join(thread[i], NULL);delete storage;delete []thread; }完整源代碼:http://download.csdn.net/download/hanqing280441589/8444613
總結(jié)
以上是生活随笔為你收集整理的Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 移动端跨平台开发框架对比分析
- 下一篇: GRUB与Linux系统修复(第二版)