“监视器是特定于语言的结构”-这是什么意思?这是否意味着它们依赖于编译器/编程语言?如果是这样,它们不能在C中实现,对吗?我被要求在C中实现一个监视器。最初虽然是一个监视器结构,但由于它不能容纳函数,它是没有用的。有人有什么想法吗?先谢了
b4lqfgs41#
有些语言内置了对同步原语的支持,也就是监视器。有些语言没有。C语言没有。它可以在C语言中实现,但它的实现最终取决于CPU和/或操作系统。
k97glaaz2#
监视器可以用C语言实现。这里有一个例子,你可以试试。
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <semaphore.h> struct monitor_DataType { sem_t OKtoRead; sem_t OKtoWrite; int readerCount; int isBusyWriting; int readRequested; }; struct monitor_DataType monitor_data; void monitor_StartWrite() { if(monitor_data.isBusyWriting || monitor_data.readerCount != 0){ sem_wait(&(monitor_data.OKtoWrite)); } monitor_data.isBusyWriting++; } void monitor_EndWrite() { monitor_data.isBusyWriting--; if(monitor_data.readRequested){ sem_post(&(monitor_data.OKtoRead)); } else { sem_post(&(monitor_data.OKtoWrite)); } } // Function that will block until read can start void monitor_StartRead() { if(monitor_data.isBusyWriting){ monitor_data.readRequested++; sem_wait(&(monitor_data.OKtoRead)); monitor_data.readRequested--; } monitor_data.readerCount++; sem_post(&(monitor_data.OKtoRead)); } // Function to signal reading is complete void monitor_EndRead() { monitor_data.readerCount--; if(monitor_data.readerCount == 0){ sem_post(&(monitor_data.OKtoWrite)); } } // intialize the monitor int monitor_Initialized(){ int returnValue = 1; // Initialize the structure monitor_data.readerCount = 0; monitor_data.isBusyWriting = 0; monitor_data.readRequested = 0; // initialize the semaphores if(sem_init(&(monitor_data.OKtoWrite), 0, 1) == 0 && sem_init(&(monitor_data.OKtoRead), 0, 1) == 0){ returnValue = 0; } else { printf("Unable to initialize semaphores\n"); } return returnValue; } // Destroys the semphores. void monitor_Destroy(){ sem_destroy(&(monitor_data.OKtoWrite)); sem_destroy(&(monitor_data.OKtoRead)); } int main() { if(monitor_Initialized() == 0){ printf("Initialized\n"); monitor_StartWrite(); printf("Writing stuffs...\n"); monitor_EndWrite(); monitor_StartRead(); printf("Reading stuffs...\n"); monitor_EndRead(); monitor_Destroy(); } return 0; }
2条答案
按热度按时间b4lqfgs41#
有些语言内置了对同步原语的支持,也就是监视器。有些语言没有。C语言没有。它可以在C语言中实现,但它的实现最终取决于CPU和/或操作系统。
k97glaaz2#
监视器可以用C语言实现。这里有一个例子,你可以试试。