IPC 经典问题:Reader & Writer Problem

Posted justsong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IPC 经典问题:Reader & Writer Problem相关的知识,希望对你有一定的参考价值。

完整代码实现:

#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define TOTAL_NUMBER 20
void *writer(void *param);
void *reader(void *param);

int reader_num = 0;
int writer_num = 0;
int reader_mutex = 0;
int unit[TOTAL_NUMBER] = {0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0};

sem_t wmutex;
sem_t mutex;

int main(int argc, char *argv[]) {
    sem_init(&mutex,0,1);
    sem_init(&wmutex,0,1);

    for (int i = 0; i < TOTAL_NUMBER; i++){
        sleep(1);
        time_t t = time(NULL);
        struct tm tm = *localtime(&t);
        if(unit[i] == 0){
            pthread_t thread_id; 
            pthread_create(&thread_id, NULL, reader, NULL);
            reader_num ++;
            printf("%d:%d:%d: Creating %dth reader.
", tm.tm_hour, tm.tm_min, tm.tm_sec, reader_num);
        }else{
            pthread_t thread_id; 
            pthread_create(&thread_id, NULL, writer, NULL);
            writer_num ++;
            printf("%d:%d:%d: Creating %dth writer.
", tm.tm_hour, tm.tm_min, tm.tm_sec, writer_num);
        }
    }
}

void *reader(void *param) {
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    printf("%d:%d:%d: NO.%u reader requires reading.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());

    sem_wait(&mutex);
        reader_mutex ++;
        if(reader_mutex == 1){
            sem_wait(&wmutex);
        }
    sem_post(&mutex);
    // Read data
    t = time(NULL);
    tm = *localtime(&t);
    printf("%d:%d:%d: NO.%u reader begins to read.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());
    sleep(1);
    t = time(NULL);
    tm = *localtime(&t);
    printf("%d:%d:%d: End of NO.%u reader for reading.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());
    sem_wait(&mutex);
        reader_mutex --;
        if(reader_mutex == 0){
            sem_post(&wmutex);
        }
    sem_post(&mutex);
}

void *writer(void *param) {
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    printf("%d:%d:%d: NO.%u writer requires writing.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());

    sem_wait(&wmutex);
    // Write data
    t = time(NULL);
    tm = *localtime(&t);
    printf("%d:%d:%d: NO.%u writer begins to write.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());
    sleep(6);
    t = time(NULL);
    tm = *localtime(&t);
    printf("%d:%d:%d: End of NO.%u writer for writing.
", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());
    sem_post(&wmutex);
}

以上是关于IPC 经典问题:Reader & Writer Problem的主要内容,如果未能解决你的问题,请参考以下文章

内网渗透-横向移动($IPC&at&schtasks)

IO流概述

信号量解决写者优先&读者优先&公平竞争(reader writer)

Java IO流--Reader流(字符输入流) & Writer流(字符输出流)

Java I/O---Reader & Writer(字符流)

android IPC通信(上)-sharedUserId&amp;&amp;Messenger