这段代码工作正常,但消费者进程不起作用,我试图获取 Producer_pid 值并检查发生了什么,但是当我编写 printf("%d ", Producer_pid) 不输入时给出两个值 它给出一个值。我对所有计算机编程都是新手,我正在自学,如果问题很糟糕,我很抱歉
我认为制作人流程并没有结束任何可以帮助我的想法?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFFER_SIZE 2
int buffer[BUFFER_SIZE];
int sayac = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void produce(int item) {
buffer[sayac] = item;
sayac++;
}
int consume() {
int item = buffer[sayac - 1];
sayac--;
return item;
}
void *producer_thread(void *arg) {
int *pipe_fd = (int *)arg;
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock(&mutex);
while (sayac == BUFFER_SIZE) {
pthread_mutex_unlock(&mutex);
usleep(100000); // Kısa bir süre bekleyerek döngüyü serbest bırak
pthread_mutex_lock(&mutex);
}
produce(i);
printf("Üretici: %d üretildi.\n", i);
write(pipe_fd[1], &i, sizeof(i));
pthread_mutex_unlock(&mutex);
sleep(1);
}
close(pipe_fd[1]);
return NULL;
}
void *consumer_thread(void *arg) {
int *pipe_fd = (int *)arg;
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock(&mutex);
while (sayac == 0) {
pthread_mutex_unlock(&mutex);
usleep(100000); // Kısa bir süre bekleyerek döngüyü serbest bırak
pthread_mutex_lock(&mutex);
}
int item = consume();
printf("Tüketici: %d tüketildi.\n", item);
int received_data;
read(pipe_fd[0], &received_data, sizeof(received_data));
pthread_mutex_unlock(&mutex);
sleep(1);
}
close(pipe_fd[0]);
return NULL;
}
int main() {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
perror("Pipe oluşturulamadı");
return 1;
}
pid_t producer_pid = fork();
printf("%d ---------------",producer_pid);
if (producer_pid == 0) {
// Yavru üretici işlem kodu
close(pipe_fd[0]); // Okuma tarafını kapat
producer_thread((void *)pipe_fd);
exit(0);
} else if (producer_pid > 0) {
pid_t consumer_pid = fork();
if (consumer_pid == 0) {
// Yavru tüketici işlem kodu
close(pipe_fd[1]); // Yazma tarafını kapat
consumer_thread((void *)pipe_fd);
exit(0);
} else if (consumer_pid > 0) {
// Ana işlem kodu
close(pipe_fd[0]); // Okuma tarafını kapat
close(pipe_fd[1]); // Yazma tarafını kapat
wait(NULL);
wait(NULL);
printf("Ana işlem tamamlandı.\n");
} else {
fprintf(stderr, "Tüketici işlem oluşturulamadı.\n");
return 1;
}
} else {
fprintf(stderr, "Üretici işlem oluşturulamadı.\n");
return 1;
}
return 0;
}
这里的主要问题是您正在打开一个 pthread 互斥锁以在使用 fork() 打开的进程之间进行同步。
pthread_mutex,顾名思义,是为了在线程之间同步而设计的。 它将无法在使用 fork 创建的进程之间同步,因为这些进程将具有不同的内存空间。
对于您的实现来说,使用 pthread_mutex 并没有多大意义。 write() 和 read() 是阻塞的,因此您可以使用管道使两个进程同步。
换个话题,当你使用 printf() 时,有时操作系统会等待并且不打印所有日志。使用 fflush() 查看所有日志。