Linux入門:線程同步與互斥(三)——信號量

POSIX版本的信號量(掛起等待鎖)

之前實現了基於單鏈表的生產者——消費者模型,這次利用POSIX版本的信號量實現基於環形隊列的生產者——消費者模型。

環形buffer:用一維數組來模擬(讓下標模上數組元素的個數來實現)

(1)環形隊列的判空判滿:

生產者與消費者的下標相同時爲空

生產者的下一個下標爲消費者的下標時爲滿

(2)當隊列爲空時必須保證生產者先運行,當隊列爲滿時必須保證消費者先運行

(3)生產者關心空格數,而消費者關心有效數據的數目


程序示例:(基於環形隊列的生產者——消費者模型)

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define SIZE 64
int ring[SIZE];
sem_t blanks, datas;

void *producer(void *arg)
{
	int i = 0;
	while(1)
	{
		sem_wait(&blanks);
        int data = rand()%1234;
		ring[i] = data;
		printf("producer done...%d\n", data);
		i++;
		i %= SIZE;
		sem_post(&datas);
		sleep(1);
	}
}

void *consumer(void *arg)
{
	int i = 0;
	while(1)
	{
		sem_wait(&datas);
		int data = ring[i];
		printf("consumer done...%d\n", data);
		i++;
		i %= SIZE;
		sem_post(&blanks);
		//sleep(1);
	}
}

int main()
{
	sem_init(&blanks, 0, SIZE);
	sem_init(&datas, 0, 0);
	pthread_t id1, id2;
	pthread_create(&id1, NULL, producer, NULL);
	pthread_create(&id2, NULL, consumer, NULL);

	pthread_join(id1, NULL);
	pthread_join(id2, NULL);
    
	sem_destroy(&blanks);
	sem_destroy(&datas);

	return 0;
}
運行結果:

1.當生產者生產的比較快時,環形隊列被填滿後,生產者就需要停下來去等待消費者消費,當消費者消費了之後生產者才能繼續生產:



2.當生產者生產的比較慢時,消費者必須等待生產者生產了之後才能消費:


發佈了76 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章