C.
#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>
int buf = 0;
sem_t *mutex, *full, *empty;
void *producer(void *arg) {
while (1) {
sem_wait(empty); // Wait for an empty slot
sem_wait(mutex); // Acquire mutex for critical section
buf++;
printf("Item produced. Count: %d\n", buf);
sem_post(mutex); // Release mutex
sem_post(full); // Signal that an item is available
}
return NULL;
}
void *consumer(void *arg) {
while (1) {
sem_wait(full); // Wait for an item to be available
sem_wait(mutex); // Acquire mutex for critical section
buf--;
printf("Item consumed. Count: %d\n", buf);
sem_post(mutex); // Release mutex
sem_post(empty); // Signal that an empty slot is available
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
// Initialize semaphores
mutex = sem_open("/mutex", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1);
full = sem_open("/full", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 0);
empty = sem_open("/empty", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 10);
// Create producer and consumer threads
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// Join threads (never reached in this example due to infinite loop in threads)
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// Close and unlink semaphores (optional, but good practice)
sem_close(mutex);
sem_close(full);
sem_close(empty);
sem_unlink("/mutex");
sem_unlink("/full");
sem_unlink("/empty");
return 0;
}
下面是一些输出:
Item consumed. Count: 1926
Item consumed. Count: 1925
Item consumed. Count: 1924
Item produced. Count: 1933
Item produced. Count: 1924
Item consumed. Count: 1923
Item consumed. Count: 1924
Item consumed. Count: 1923
Item consumed. Count: 1922
Item consumed. Count: 1921
Item consumed. Count: 1920
我把空的sem设为10,所以把它扩展为buf限制. 为什么yields 超过了极限?
一切都是照课本做的. 在macbook air m1上,所以sem_init不能工作,使用sem_open代替