C + + multithreaded synchronization (with event object events) __c++

Source: Internet
Author: User
Tags ticket

C + + multithreaded synchronization (with event object events)

#include <Windows.h> #include <iostream> using namespace std; DWORD WINAPI Fun1proc (LPVOID lpparameter);//thread 1 's entry function DWORD WINAPI Fun2proc (LPVOID lpparameter);//thread 2 's entry function int G_ticke
	TS = 100;//Total Ticket number HANDLE g_hevent;//Global event object void Main () {HANDLE hThread1;

	HANDLE hThread2;

	Create an automatic reset event kernel Object g_hevent = CreateEvent (Null,false, FALSE, "tickets"); Ensure that the application has only one instance if (g_hevent) {if (error_already_exists = = GetLastError ()) {cout<< Only one instance can run.
			"<<endl;
		Return
	} setevent (g_hevent);//Set event object to have signal//create thread hThread1 = CreateThread (null, 0, fun1proc, NULL, 0, NULL);
	HThread2 = CreateThread (null, 0, fun2proc, NULL, 0, NULL);

	CloseHandle (HTHREAD1);//does not terminate the running of the thread; When the thread handle is no longer needed, it should be closed so that the reference count of the thread kernel object is reduced by 1 CloseHandle (HTHREAD2);

	Let the main thread sleep 4 second Morpheus (4000);

Closes the event object handle CloseHandle (G_hevent);
		DWORD WINAPI Fun1proc (LPVOID lpparameter) {while (TRUE) {//Request Event Object WaitForSingleObject (G_hevent,infinite);
			if (g_tickets>0) {sleep (1); cout<< "Thread1 Sell ticket:" <<g_tickets--<<endl;
		SetEvent (g_hevent);
			else {setevent (g_hevent);
		Break
} return 0;
		DWORD WINAPI Fun2proc (LPVOID lpparameter) {while (TRUE) {//Request Event Object WaitForSingleObject (G_hevent,infinite);
			if (g_tickets>0) {sleep (1);
			cout<< "Thread2 Sell ticket:" <<g_tickets--<<endl;
		SetEvent (g_hevent);
			else {setevent (g_hevent);
		Break
} 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.