The synchronization mechanism between producer and consumer in Windows

Source: Internet
Author: User

For the moment, let's take the following example:

Class cuploadsongroad{
HANDLE Buffer_full;
HANDLE Buffer_empty;
int m_nroadnum;
Critical_section SC, OC;

int *buffer;
int buffer_p;
int buffer_c;
int p;
int C;

Public
Cuploadsongroad () {}
Cuploadsongroad (int n): M_nroadnum (N)
{
Buffer = new Int[m_nroadnum];
memset (buffer, 0, m_nroadnum*sizeof (int));
Buffer_full = CreateSemaphore (null, m_nroadnum, m_nroadnum, NULL);
Buffer_empty = CreateSemaphore (null, 0, m_nroadnum, NULL);
InitializeCriticalSection (&SC);
InitializeCriticalSection (&OC);
Buffer_c = c = 0;

for (int i=0; i<n; i++) {
Buffer[i] = i;
}
buffer_p = p = n;
}
~cuploadsongroad ()
{
delete []buffer;
DeleteCriticalSection (&AMP;SC);
DeleteCriticalSection (&AMP;OC);
CloseHandle (Buffer_full);
CloseHandle (Buffer_empty);
}


unsigned int produce () {

WaitForSingleObject (Buffer_empty, INFINITE);

EnterCriticalSection (&AMP;SC);

Buffer[buffer_p] = p;
printf ("producer produces \t%d\n", buffer[buffer_p]);
Buffer_p = (++p)% M_nroadnum;

LeaveCriticalSection (&AMP;SC);

ReleaseSemaphore (Buffer_full, 1, NULL);

return 0;
}

unsigned int consume () {

WaitForSingleObject (Buffer_full, 10*60*1000);

EnterCriticalSection (&AMP;SC);

printf ("T consumer consumes \t%d\n", buffer[buffer_c]);
Buffer_c = (++c)% M_nroadnum;

LeaveCriticalSection (&AMP;SC);

ReleaseSemaphore (Buffer_empty, 1, NULL);

return 0;
}

};

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.