对多线程并发的模拟:
1、 创建5个线程,sleep一个随机的时间后,对同一个文件写。
2、
创建另外1个线程,读出5个线程写的文件内容。
3、 使用信号量同步多线程之间的并发,要求没写一次,读取一次。
文件读出的内容大致如下所示:
线程5写进文件,数值为:;4个这个星号
线程3写进文件,数值为:;4个这个星号
线程2写进文件,数值为:*;4个这个星号
基于Monster 组和GPT的调写:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_THREADS 5
#define FILENAME "test.txt"
char data[NUM_THREADS][20] = {"线程1写进文件,数值为:", "线程2写进文件,数值为:*", "线程3写进文件,数值为:", "线程4写进文件,数值为:", "线程5写进文件,数值为:"};
sem_t write_sem, read_sem;
FILE* fp;
void* write_file(void* arg) {
int id = *(int*) arg;
int sleep_time = rand() % 5 + 1; // 随机睡眠时间
sleep(sleep_time);
sem_wait(&write_sem);
fprintf(fp, "%s", data[id]);
for (int i = 0; i < 4; i++) {
fprintf(fp, "★");
}
fprintf(fp, "\n");
fflush(fp);
sem_post(&read_sem);
pthread_exit(NULL);
}
void* read_file(void* arg) {
char buffer[1024];
sem_wait(&read_sem);
fseek(fp, 0, SEEK_SET);
while (fgets(buffer, sizeof(buffer), fp)) {
printf("%s", buffer);
}
sem_post(&write_sem);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS+1];
int thread_ids[NUM_THREADS+1];
fp = fopen(FILENAME, "w+");
if (fp == NULL) {
printf("无法打开文件 %s\n", FILENAME);
exit(EXIT_FAILURE);
}
sem_init(&write_sem, 0, 1);
sem_init(&read_sem, 0, 0);
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, write_file, (void*) &thread_ids[i]);
}
pthread_create(&threads[NUM_THREADS], NULL, read_file, NULL);
for (int i = 0; i < NUM_THREADS+1; i++) {
pthread_join(threads[i], NULL);
}
sem_destroy(&write_sem);
sem_destroy(&read_sem);
fclose(fp);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: