读者编写者问题:每次都获得不同的输出

时间:2011-05-08 13:40:24

标签: c semaphore

我在C语言中使用信号量为Reader-Writer的问题编写了简单的解决方案。但是每次成功运行后我都会得到不同的输出。这背后的确切原因是什么?这是代码:

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

sem_t x,wsem;
int rc;

void *reader(void *);
void *writer(void *);

int svar=0;

int main()
{
    pthread_t w[2],r[3];
    sem_init(&x,0,1);
    sem_init(&wsem,0,1);

    rc=0;

    pthread_create(&w[0],NULL,writer,(void *)0);
    pthread_create(&r[0],NULL,reader,(void *)0);
    pthread_create(&w[1],NULL,writer,(void *)1);
    pthread_create(&r[1],NULL,reader,(void *)1);
    pthread_create(&r[2],NULL,reader,(void *)2);

    pthread_join(r[0],NULL);
    pthread_join(w[0],NULL);
    pthread_join(w[1],NULL);
    pthread_join(r[1],NULL);
    pthread_join(r[2],NULL);

    sem_destroy(&x);
    sem_destroy(&wsem);

    return 0;
}

void *reader(void *arg)
{

        printf("\nReader is executing......");
        sem_wait(&x);
        rc++;
        if (rc == 1)
        sem_wait(&wsem);
        sem_post(&x);
        printf("Reader-%d : value of shared variable : %d\n", (int)arg,svar);
        sem_wait(&x);
        rc--;
        if (rc==0)
            sem_post(&wsem);
        sem_post(&x);

}

void *writer(void *arg)
{

        printf("\nWriter is executing......");
        sem_wait(&wsem);
        svar=svar+5;
        printf("Writer-%d : value of shared variable : %d\n",(int)arg,svar);
        sem_post(&wsem);

}

Output1 : 
Writer is executing......Writer-0 : value of shared variable : 5

Reader is executing......Reader-0 : value of shared variable : 5

Reader is executing......Reader-1 : value of shared variable : 5

Writer is executing......Writer-1 : value of shared variable : 10

Reader is executing......Reader-2 : value of shared variable : 10

Output2: 

Writer is executing......Writer-0 : value of shared variable : 5

Writer is executing......Writer-1 : value of shared variable : 10

Reader is executing......Reader-1 : value of shared variable : 10

Reader is executing......Reader-0 : value of shared variable : 10

Reader is executing......Reader-2 : value of shared variable : 10 

Output3:

Writer is executing......Writer-0 : value of shared variable : 5

Writer is executing......Writer-1 : value of shared variable : 10

Reader is executing......Reader-1 : value of shared variable : 10

Reader is executing......Reader-0 : value of shared variable : 10

Reader is executing......Reader-2 : value of shared variable : 10

1 个答案:

答案 0 :(得分:5)

线程执行是非确定性的。仅仅因为您按特定顺序启动了线程并不意味着它们将以该顺序执行。在这种情况下,您构建信号量和条件变量的方式意味着一旦第一个作者编写完成,那么一个或多个作者可以编写,或者一个或多个读者可以按特定顺序阅读。