编写一个程序,实现如下功能:包含一个生产者线程和一个消费者线程,它们有一个共享缓冲区;共享缓冲区是一个长度为10的字符型数组,该数组为全局变量;生产者从键盘获取一个用户输入的字符串(长度不超过255字符),然后将字符串逐字符地存入共享缓冲区;消费者从共享缓冲区中逐字符地读取并打印字符;当检测到输入字符串中的‘!”时,结束程序。
时间: 2024-02-22 17:58:52 浏览: 77
好的,我来为您编写这个程序。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#define BUFFER_SIZE 10
char buffer[BUFFER_SIZE];
int buffer_index = 0;
pthread_mutex_t mutex;
pthread_cond_t buffer_full;
pthread_cond_t buffer_empty;
void produce(char item) {
pthread_mutex_lock(&mutex);
while (buffer_index == BUFFER_SIZE) {
pthread_cond_wait(&buffer_full, &mutex);
}
buffer[buffer_index++] = item;
pthread_cond_signal(&buffer_empty);
pthread_mutex_unlock(&mutex);
}
char consume() {
pthread_mutex_lock(&mutex);
while (buffer_index == 0) {
pthread_cond_wait(&buffer_empty, &mutex);
}
char item = buffer[--buffer_index];
pthread_cond_signal(&buffer_full);
pthread_mutex_unlock(&mutex);
return item;
}
void *producer(void *param) {
char input[256];
printf("Enter some text. Enter '!' or '\"' to exit.\n");
fgets(input, 256, stdin);
int input_len = strlen(input);
for (int i = 0; i < input_len; i++) {
produce(input[i]);
}
pthread_exit(0);
}
void *consumer(void *param) {
char item;
do {
item = consume();
printf("%c", item);
} while (item != '!' && item != '\"');
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&buffer_full, NULL);
pthread_cond_init(&buffer_empty, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&buffer_full);
pthread_cond_destroy(&buffer_empty);
return 0;
}
```
运行程序后,输入一些文本,生产者线程将其逐字符存入共享缓冲区,消费者线程逐字符读取并打印输出。当输入文本中出现 '!' 或 '\"' 字符时,消费者线程退出循环并结束程序。程序中使用互斥锁和条件变量实现了线程间的同步。
阅读全文