操作系统的同步互斥编程

读者写者问题

参考链接  http://c.biancheng.net/cpp/html/2601.html

读者优先

[ligang@localhost ~]$ cat read.c 
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/time.h>
#include<semaphore.h>

pthread_mutex_t mutex;
sem_t rw;
int delay = 1;
int counter=0;

void *writer(void *param)
{

        sem_wait(&rw);
        printf("it is writting!!!\n");
        usleep(2000000);
        sem_post(&rw);
        sleep(4);

        return NULL;

}

void *reader(void *parm)
{
        pthread_mutex_lock(&mutex);
        if(counter==0)
        {
                sem_wait(&rw);
        }
        counter++;
        printf("add the [%d] reader\n",counter);
        pthread_mutex_unlock(&mutex);

        usleep(2000000);

        printf("it is reading\n");

        pthread_mutex_lock(&mutex);
        printf("delete the [%d] reader\n",counter);
        counter--;
        if(counter==0)
        {
                sem_post(&rw);
        }
        pthread_mutex_unlock(&mutex);

        return NULL;
}

int main()
{
        pthread_t tid_w,tid_r;
        void *retval;
        pthread_mutex_init(&mutex,NULL);
        sem_init(&rw,0,1);
        pthread_create(&tid_w,NULL,writer,NULL);
        pthread_create(&tid_r,NULL,reader,NULL);

        pthread_create(&tid_r,NULL,reader,NULL);
        pthread_create(&tid_w,NULL,writer,NULL);
        pthread_join(tid_w,&retval);
        pthread_join(tid_r,&retval);
        return 0;
}

  缺点无法解决两者之间的并发问题

运行结果

[ligang@localhost ~]$ gcc read.c -lpthread
[ligang@localhost ~]$ ./a.out
it is writting!!!
add the [1] reader
add the [2] reader
it is reading
delete the [2] reader
it is reading
delete the [1] reader
it is writting!!!

posted @ 2018-11-30 17:17  李刚blog  阅读(310)  评论(0编辑  收藏  举报