- 论坛徽章:
- 14
|
本帖最后由 lxyscls 于 2012-07-30 10:09 编辑
基本模型为UNP V2上面的实现
1、1000000次写和读,从0写到1000000,同样从0读到1000000,如果读数有错误消费者报错
2、缓冲区数组大小10,循环写入,循环读出,buf[n % 10] = n,读出按同样的方式进行检查
模型A(UNPV2上面已实现,使用POSIX信号量)- struct { /* data shared by producers and consumers */
- int buff[NBUFF];
- int nput; /* item number: 0, 1, 2, ... */
- int nputval; /* value to store in buff[] */
- int nget; /* item number: 0, 1, 2, ... */
- int ngetval; /* value fetched from buff[] */
- sem_t mutex, nempty, nstored; /* semaphores, not pointers */
- } shared;
复制代码 nput, nputval供生产者使用,nget,ngetval供消费者使用,nempty表示缓冲区中空位置,nstored表示缓冲区中已存个数,mutex锁操作- /* 4initialize three semaphores */
- Sem_init(&shared.mutex, 0, 1);
- Sem_init(&shared.nempty, 0, NBUFF);
- Sem_init(&shared.nstored, 0, 0);
复制代码 生产者线程函数:- /* include produce */
- void *
- produce(void *arg)
- {
- for ( ; ; ) {
- Sem_wait(&shared.nempty); /* wait for at least 1 empty slot */
- Sem_wait(&shared.mutex);
- if (shared.nput >= nitems) {
- Sem_post(&shared.nstored); /* let consumers terminate */
- Sem_post(&shared.nempty);
- Sem_post(&shared.mutex);
- return(NULL); /* all done */
- }
- shared.buff[shared.nput % NBUFF] = shared.nputval;
- shared.nput++;
- shared.nputval++;
- Sem_post(&shared.mutex);
- Sem_post(&shared.nstored); /* 1 more stored item */
- *((int *) arg) += 1;
- }
- }
- /* end produce */
复制代码 消费者线程函数:- /* include consume */
- void *
- consume(void *arg)
- {
- int i;
- for ( ; ; ) {
- Sem_wait(&shared.nstored); /* wait for at least 1 stored item */
- Sem_wait(&shared.mutex);
- if (shared.nget >= nitems) {
- Sem_post(&shared.nstored);
- Sem_post(&shared.mutex);
- return(NULL); /* all done */
- }
- i = shared.nget % NBUFF;
- if (shared.buff[i] != shared.ngetval)
- printf("error: buff[%d] = %d\n", i, shared.buff[i]);
- shared.nget++;
- shared.ngetval++;
- Sem_post(&shared.mutex);
- Sem_post(&shared.nempty); /* 1 more empty slot */
- *((int *) arg) += 1;
- }
- }
复制代码 问题1(结合后续mutex实现发问):该模型在消费者/生产者线程数目对等情况下,基本上运行时间保持不变,即10消费者/10生产者 和 50消费者/50生产者 基本运行时间差别不大
问题2:该模型在生产者/消费者线程数目出现差异时,运行时间明显恶化,即10消费者/50生产者 或 50消费者/10生产者 比10/10或50/50运行慢,请问这是为什么嗫?因为线程过多调度的问题么?但是为什么10/50线程的调度比50/50还要慢?
原因A:消费者/生产者线程 被调用机会均等,如果出现巨大差异时,则相对来讲线程数少的XX者得到调度的机会减小,导致整体性能下降?
排除该原因,测试表明生产者/消费者 线程组 彼此相对独立,线程增多的组别恶化明显
问题3:如果把生产/消费的shared.mutex分开为两个,即生产/消费的读写操作使用独立的mutex,因为有nstored和nempty的保护,修改证明可行,但是运行时间无优化,这又是为什么呢?按道理生产者/消费者独立调度应该有提升才对——实际测量有10%——20%的提升,还是有优化的! |
|