线程的执行的无序性---生产消费者

源程序:

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <semaphore.h>
#define BUFSIZE 4
#define NUMBER 8
int sum_of_number=0;
sem_t write_res_number;
sem_t read_res_number;
struct recycle_buffer
{
    int buffer[BUFSIZE];
    int head,tail;   
}re_buf;
pthread_mutex_t buffer_mutex=PTHREAD_MUTEX_INITIALIZER;
void *prod(void *arg)
{
    int i;
    for(i=0;i<=8;i++)
    {
        sem_wait(&write_res_number);
        pthread_mutex_lock(&buffer_mutex);
        re_buf.buffer[re_buf.tail]=i;
        re_buf.tail=(re_buf.tail+1)%BUFSIZE;
        printf("procuder  %d  write %d./n",(int)pthread_self(),i);
        pthread_mutex_unlock(&buffer_mutex);
        sem_post(&read_res_number);
    }
    return NULL;
}
void *consumer(void *arg)
{
    int i,num;
    for(i=0;i<=8;i++)
    {
        sem_wait(&read_res_number);
        pthread_mutex_lock(&buffer_mutex);
        num=re_buf.buffer[re_buf.head];
        re_buf.head=(re_buf.head+1)%BUFSIZE;
        printf("consumer %d read %d./n",(int)pthread_self(),num);
        pthread_mutex_unlock(&buffer_mutex);
        sum_of_number+=num;
        sem_post(&write_res_number);
    }
    return NULL;
}
int main()
{
    pthread_t pid,cid;
    int i;
    re_buf.head=0;
    re_buf.tail=0;
    for(i=0;i<BUFSIZE;i++)
        re_buf.buffer[i]=0;
    sem_init(&write_res_number,0,BUFSIZE);
    sem_init(&read_res_number,0,0);
    pthread_create(&pid,NULL,prod,NULL);
    pthread_create(&cid,NULL,consumer,NULL);
    pthread_join(pid,NULL);
    pthread_join(cid,NULL);
    printf("the sum of number is %d/n",sum_of_number);
    for(i=0;i<4;i++)
    printf("%d/n",re_buf.buffer[i]);
    return 0;
   
}
运行结果:

1。

procuder  -1210569840  write 0.
procuder  -1210569840  write 1.
consumer -1218962544 read 0.
procuder  -1210569840  write 2.
consumer -1218962544 read 1.
consumer -1218962544 read 2.
procuder  -1210569840  write 3.
procuder  -1210569840  write 4.
procuder  -1210569840  write 5.
procuder  -1210569840  write 6.
consumer -1218962544 read 3.
consumer -1218962544 read 4.
consumer -1218962544 read 5.
consumer -1218962544 read 6.
procuder  -1210569840  write 7.
procuder  -1210569840  write 8.
consumer -1218962544 read 7.
consumer -1218962544 read 8.
the sum of number is 36
8
5
6
7
2。

procuder  -1209984112  write 0.
procuder  -1209984112  write 1.
procuder  -1209984112  write 2.
procuder  -1209984112  write 3.
consumer -1218376816 read 0.
consumer -1218376816 read 1.
consumer -1218376816 read 2.
consumer -1218376816 read 3.
procuder  -1209984112  write 4.
procuder  -1209984112  write 5.
procuder  -1209984112  write 6.
procuder  -1209984112  write 7.
consumer -1218376816 read 4.
consumer -1218376816 read 5.
consumer -1218376816 read 6.
consumer -1218376816 read 7.
procuder  -1209984112  write 8.
consumer -1218376816 read 8.
the sum of number is 36
8
5
6
7

发布了18 篇原创文章 · 获赞 0 · 访问量 48万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览