Producerconsumer problem is implemented under Windows2000

xiaoxiao2021-03-06  46

I. Problem Description Producer - Consumer Problem is a classic process synchronization problem, which is first proposed by Dijkstra to demonstrate his proposed semaphore. This job requires two threads executed in the same process address space. Producer threads produces items, then place the item in an air buffer for consumer thread consumption. The consumer thread obtains items from the buffer and then releases the buffer. When the producer thread produces items, if there is no air buffer available, the producer thread must wait for the consumer thread to release an air buffer. When consumer thread consumement items, if there is no full buffer, the consumer thread will be blocked until the new item is produced.

Second, implementation code 0000 #include 0001 #include 0002 0003 const unsigned short SIZE_OF_BUFFER = 10; // buffer length 0004 unsigned short ProductID = 0; // Number 0005 unsigned short ConsumeID = 0; // will be consumed product number 0006 unsigned short in = 0; // Product into the subscript 0007 unsigned short out = 0; // Products 标 冲;; // Buffer is a loop queue 0010 bool g_continue = true; // Control program end 0011 handle g_hmutex; // Used to be mutually exclusive 0012 handle g_hfullitems; // buffer 项 项 项 项 项 g Empty item 0014 0015 DWORD WINAPI PRODUCER (LPVOID); // Producer Thread 0016 DWORD WINAPI Consumer (LPVOID); // Consumer Thread 0017 0018 INT Main () 0019 {0020 // Create Each Mutual Exclusion Signal 0021 G_hmutex = Createmutex (NULL, FALSE, NULL); 0022 g_hfullitems = CreateSemaphore (NULL, 0, SIZE_OF_Buffer, NULL); 0023 g_hemptyitems = CreateSemaphore (null, size_of_buffer, 0024 size_of_buffer, null); 0025 0026 // Buffer initialization 0027 for (INT i = 0; I

0038 0039 Handle Hthreads [THREADS_COUNT]; // Handle0040 DWORD PRODUCERID [Products_count]; // Producer Thread Identifier 0041 DWORD Consumerid [consuMERS_COUNT]; // Consumer thread identifier 0042 0043 // Create a producer Thread 0044 for (int i = 0; i

Simply simulate, only the ID number of the new product is output 0066 void products () 0067 {0068 st: cout << "products" << products << "..."; 0069 std :: cout << " Succeed << std :: endl; 0070} 0071 0072 // put the new product into buffer 0073 void append () 0074 {0075 std :: cout << "appending a product ..."; 0076 g_buffer [ IN] = productID; 0077 IN = (in 1)% size_of_buffer; 0078 std :: couk << "succeed << std :: endl; 0079 0080 // Output buffer current status 0081 for (int i = 0 i

转载请注明原文地址:https://www.9cbs.com/read-79876.html

New Post(0)