C + + programming simulation producer Consumer model __linux

Source: Internet
Author: User
Tags mutex pear rand semaphore
Producer consumer problem is a typical process synchronization mutex problem in operating system, (English: Producer-consumer problem), also called limited buffer problem (English: Bounded-buffer problem), it is a classic case of multithreading synchronization problem.

This issue describes the problems that occur when the two thread "producer" (Producer) and "consumer" (Consumer) that share a fixed size buffer are actually running.

The primary role of the producer is to generate a certain amount of data into the buffer, and then repeat the process. Consumers, meanwhile, are consuming the data in the buffer zone.

The constraint of the problem is to ensure that the producer does not add data when the buffer is full, nor does the consumer consume data in the buffer when it is empty.

The following C + + program code uses the example of a fruit to simulate producer consumer models, producers randomly producing fruit lists {"Apple", "Banana", "Cherry", "Orange", "Pear", "Peach", "Watermelon"}, The buffer is modeled with an array.

The program applies mutexes and semaphores, and uses the thread functions under windows such as Createmutex,releasemutex,createsemaphore,releasesemaphore,waitforsingleobject.

C + + code is as follows: #include <iostream> #include <cstdlib> #include <windows.h> #include <string> #include <time.h> using namespace std; const int limit = 30; Total production const int MAXSIZE = 10; Buffer size const int kind = 7; int bufidx = 0; Current buffer subscript string buf[maxsize]; Buffer (String)//Forged product string product[] = {"Apple", "Banana", "Cherry", "Orange", "Pear", "Peach", "Watermelon"}; HANDLE Mutex,full,empty; HANDLE disp; Mutex/producer child procedure for controlling screen printing DWORD winapi Producer (lpvoid param) {int ct,idx; const int pwait = Srand (Time (NULL));//Random multicast Species WaitForSingleObject (disp, INFINITE); cout << "Producer start!" << Endl << Endl; ReleaseMutex (disp); for (ct = 0; ct < limit; ct + +) {idx = rand ()% kind; WaitForSingleObject (disp, INFINITE); cout << Product[idx] << "is ready!" << Endl << Endl; ReleaseMutex (disp); WaitForSingleObject (empty, INFINITE); Request an empty buffer, blocking WaitForSingleObject (mutex, INFINITE); Request mutual exclusion Lock, blocking BUF[BUFIDX + +] = Product[idx]; WaitForSingleObject (disp, INFINITE); cout << Product[idx] << "added to slot No." << bufidx << endl << Endl; ReleaseMutex (disp); ReleaseMutex (mutex); Releases the mutex ReleaseSemaphore (full, 1, NULL); Signal (full) sleep (rand ()% pwait + 100); Take a break} cout << "Producer quit!" << Endl << Endl; return 0; }//Consumer sub process DWORD winapi Consumer (lpvoid param) {int ct; const int cwait =; string stuff; Srand (Time (NULL)); WaitForSingleObject (disp, INFINITE); cout << "Consumer start!" << Endl << Endl; ReleaseMutex (disp); for (ct = 0; ct < limit; ct + +) {WaitForSingleObject (full, INFINITE);//Request a filled buffer, block WaitForSingleObject (mutex, Infinit E); Request mutual exclusion lock, blocking stuff = buf[--Bufidx]; WaitForSingleObject (disp, INFINITE); cout << "Consumer get" << stuff << "from slot No." << (Bufidx + 1) << Endl << Endl; ReleaseMutex (disp); ReleaseMutex (mutex); Release the mutex ReleaseSemaphore (empty, 1, NULL); Signal (empty) SLeep (rand ()% cwait + 100); Take a break} cout << "Consumer quit!" << Endl << Endl; return 0; int main () {//producer thread thread ID DWORD producerid with consumer thread, Consumerid//thread handle HANDLE producerhandle, consumerhandle;//create producer thread Pr Oducerhandle = CreateThread (null, 0, Producer, NULL, 0, &producerid); Create consumer thread consumerhandle = CreateThread (null, 0, Consumer, NULL, 0, &consumerid); DISP = CreateMutex (null, FALSE, NULL); Create a mutex mutex = CreateMutex (null, FALSE, NULL); Create buffer occupancy semaphore full = CreateSemaphore (NULL, 0, maxsize, "full"); Create buffer idle semaphore empty = CreateSemaphore (NULL, MaxSize, MaxSize, "empty"); Wait until producer thread execution completes if (Producerhandle!= NULL) {WaitForSingleObject (Producerhandle, INFINITE); CloseHandle (Producerhandle); }//wait until consumer thread execution completes if (Consumerhandle!= NULL) {WaitForSingleObject (Consumerhandle, INFINITE); CloseHandle (Consumerhandle); System ("pause"); }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.