//*************************************************************** // illustrates two processes cooperating in a producer/consumer relationship // This code demonstrates the parent side of handle inheritance. // The producer/consumer relationship is managed by two semaphores // EMPTY and FULL, When EMPTY the producer can produce into empty buffer, // when FULL the consumer can consume buffer. // Buffers are passed through shared memory implemented as a memory mapped file // AUTHOR: Chris Wild // DATE: September 10, 1997 //*************************************************************** #include #include #include const int NBUFFERS = 3; // allow 3 buffers for bounded buffer typedef struct{ int bufID; int bufValue; } Buffer; void main(void) { HANDLE empty, full; HANDLE mapFileHandle; Buffer* commonBuffers; // Create the semaphores empty = CreateSemaphore(0,NBUFFERS,NBUFFERS, "NTcourse.semaphore.empty"); full = CreateSemaphore(0,0,NBUFFERS, "NTcourse.semaphore.full"); cout << "created semaphores\n"; // create in-memory file for Interprocess Communications mapFileHandle = CreateFileMapping( (HANDLE) 0xFFFFFFFF, // unnamed file maps to virtual memory 0, // security PAGE_READWRITE, // access to file 0, // high word of file size NBUFFERS*sizeof(Buffer), // size of memory mapped area "commonBuffer"); // name it to share with other processes commonBuffers = (Buffer*) MapViewOfFile(mapFileHandle, FILE_MAP_WRITE, 0, // High offset 0, // Low offest 0); // 0 for mapping entire file // enter a loops producing some things int bufN = 0; for(int i = 0; i < 10; i++) { // First wait for previous resource to be empty (consumed) cout << "PRODUCER: waiting for empty buffer\n"; WaitForSingleObject(empty, INFINITE); commonBuffers[bufN].bufID = bufN; commonBuffers[bufN].bufValue = 1000*i; bufN = (bufN+1) % NBUFFERS; // Have empty resource - use it to produce // put code here to produce something cout << "PRODUCER: producing a new buffer\n"; ReleaseSemaphore(full,1,0); // signals production } CloseHandle(empty); CloseHandle(full); CloseHandle(mapFileHandle); }