完整代码实现:
#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.\n", 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.\n", 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.\n", 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.\n", 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.\n", 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.\n", 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.\n", 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.\n", tm.tm_hour, tm.tm_min, tm.tm_sec, pthread_self());
sem_post(&wmutex);
}
原文地址:https://www.cnblogs.com/justsong/p/12219775.html
时间: 2024-09-30 17:21:29