- 論壇徽章:
- 0
|
本帖最后由 Unix_C_Linux 于 2015-10-20 17:36 編輯
情景:緩沖區(qū)放入1000數(shù), 生產(chǎn)者和消費者操作分別存取
1.當生產(chǎn)者和消費者數(shù)量是1:1時,寫數(shù)據(jù)記錄和讀數(shù)據(jù)記錄相等,都是1000
2.當生產(chǎn)者和消費者數(shù)量是1:N時,寫數(shù)據(jù)的數(shù)量是1000,為什么讀數(shù)據(jù)的數(shù)量之和大于1000?很多都是重復的,多個線程間是有鎖和條件變量的,為什么會讀出同樣的數(shù)據(jù)啊?
代碼如下,編譯后可以直接運行。- #include <stdio.h>
- #include <stdlib.h>
- #define BUFFER_SIZE 16 // 緩沖區(qū)數(shù)量
- struct prodcons
- {
- // 緩沖區(qū)相關(guān)數(shù)據(jù)結(jié)構(gòu)
- int buffer[BUFFER_SIZE]; /* 實際數(shù)據(jù)存放的數(shù)組*/
- pthread_mutex_t lock; /* 互斥體lock 用于對緩沖區(qū)的互斥操作 */
- int readpos, writepos; /* 讀寫指針*/
- pthread_cond_t notempty; /* 緩沖區(qū)非空的條件變量 */
- pthread_cond_t notfull; /* 緩沖區(qū)未滿的條件變量 */
- };
- /* 初始化緩沖區(qū)結(jié)構(gòu) */
- void init(struct prodcons *b)
- {
- pthread_mutex_init(&b->lock, NULL);
- pthread_cond_init(&b->notempty, NULL);
- pthread_cond_init(&b->notfull, NULL);
- b->readpos = 0;
- b->writepos = 0;
- }
- /* 將產(chǎn)品放入緩沖區(qū),這里是存入一個整數(shù)*/
- void put(struct prodcons *b, int data)
- {
- pthread_mutex_lock(&b->lock);
- /* 等待緩沖區(qū)未滿*/
- if ((b->writepos + 1) % BUFFER_SIZE == b->readpos)
- {
- pthread_cond_wait(&b->notfull, &b->lock);
- }
-
- if(data != -1){
- printf("putdata\n");
- }
- /* 寫數(shù)據(jù),并移動指針 */
- b->buffer[b->writepos] = data;
- b->writepos = (b->writepos + 1)%BUFFER_SIZE;
- /* 設置緩沖區(qū)非空的條件變量*/
- pthread_cond_signal(&b->notempty);
- pthread_mutex_unlock(&b->lock);
- }
- /* 從緩沖區(qū)中取出整數(shù)*/
- int get(struct prodcons *b)
- {
- int data;
- pthread_mutex_lock(&b->lock);
- /* 等待緩沖區(qū)非空*/
- if (b->writepos == b->readpos)
- {
- pthread_cond_wait(&b->notempty, &b->lock);
- }
- /* 讀數(shù)據(jù),移動讀指針*/
- data = b->buffer[b->readpos];
- if(data != -1){
- printf("getdata\n", data);
- }
- b->readpos = (b->readpos + 1) % BUFFER_SIZE;
- /* 設置緩沖區(qū)未滿的條件變量*/
- pthread_cond_signal(&b->notfull);
- pthread_mutex_unlock(&b->lock);
- return data;
- }
- /* 測試:生產(chǎn)者線程將1 到10000 的整數(shù)送入緩沖區(qū),消費者線
- 程從緩沖區(qū)中獲取整數(shù),兩者都打印信息*/
- #define OVER ( - 1)
- struct prodcons buffer;
- void *producer(void *data)
- {
- int n;
- for (n = 0; n < 1000; n++)
- {
- //printf("%d --->\n", n);
- put(&buffer, n);
- }
- put(&buffer, OVER);
- put(&buffer, OVER);
- put(&buffer, OVER);
- return NULL;
- }
- void *consumer(void *data)
- {
- int d;
- while (1)
- {
- d = get(&buffer);
- if (d == OVER)
- break;
- // printf("xxx|%d\n", d);
- }
- return NULL;
- }
- int main(void)
- {
- pthread_t th_a, th_b, th_c, th_d;
- void *retval;
- init(&buffer);
- /* 創(chuàng)建生產(chǎn)者和消費者線程*/
- pthread_create(&th_a, NULL, producer, 0);
- pthread_create(&th_b, NULL, consumer, 0);
- pthread_create(&th_c, NULL, consumer, 0);
- pthread_create(&th_d, NULL, consumer, 0);
- /* 等待四個線程結(jié)束*/
- pthread_join(th_a, &retval);
- pthread_join(th_b, &retval);
- pthread_join(th_c, &retval);
- pthread_join(th_d, &retval);
- return 0;
- }
復制代碼 |
|