C + + interprocess communication (common understanding example)-Buy tickets

Source: Internet
Author: User

#include "stdafx.h"


#include <iostream>
using namespace Std;


#include "Windows.h"

int index = 0;
int tickets = 100;
HANDLE Hmutex = null;//Mutex
HANDLE hevent = null;//Event

Critical_section G_cs; Critical section


DWORD WINAPI Func1 (LPVOID pparam)
{

while (true)

{

WaitForSingleObject (Hmutex, INFINITE);

WaitForSingleObject (Hevent,infinite);

EnterCriticalSection (&g_cs);

if (tickets> 0)

{

Sleep (1);

cout<< "Thread1 Sell tickets:" <<tickets--<<endl;

}

Else

Break

ReleaseMutex (Hmutex);

SetEvent (hevent);

LeaveCriticalSection (&g_cs);

}

return 0;

}

DWORD WINAPI Func2 (LPVOID pparam)

{

while (true)

{

WaitForSingleObject (Hmutex,infinite);

WaitForSingleObject (Hevent,infinite);

EnterCriticalSection (&g_cs);

if (tickets> 0)

{

Sleep (1);

cout<< "Thread2 Sell tickets:" <<tickets--<<endl;

}

Else

Break

ReleaseMutex (Hmutex);

SetEvent (hevent);

LeaveCriticalSection (&g_cs);

}

return 0;

}

void Main ()

{

HANDLE hThread1 =createthread (null, 0, FUNC1, NULL, 0, NULL);

HANDLE hThread2 =createthread (null, 0, FUNC2, NULL, 0, NULL);

CloseHandle (HTHREAD1);

CloseHandle (HTHREAD2);

Hmutex = CreateMutex (null,false,null);

Hevent =createevent (NULL, FALSE, true,null);

InitializeCriticalSection (&g_cs);

Sleep (4000);

DeleteCriticalSection (&g_cs);

}

C + + interprocess communication (common understanding example)-Buy tickets

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.