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