⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sam_sp_44_cri.cpp

📁 专题讲座四:内容包括为什么需要多进程或线程 、进程控制、线程控制、进程或线程间同步、进程间通信等。附例程。
💻 CPP
字号:
// sam_sp_44_cri.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "sam_sp_44_cri.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object
int iCounter=0;
CRITICAL_SECTION criCounter;

DWORD threadA(void* pD)
{
	int iID=(int)pD;
	for(int i=0;i<8;i++)
	{
		EnterCriticalSection(&criCounter);
		int iCopy=iCounter;
		Sleep(100);
		iCounter=iCopy+1;
		printf("thread %d : %d\n",iID,iCounter);
		LeaveCriticalSection(&criCounter);
	}
	return 0;
}

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		cerr << _T("Fatal Error: MFC initialization failed") << endl;
		nRetCode = 1;
	}
	else
	{
		//创建临界区
		InitializeCriticalSection(&criCounter);
		//创建线程
		HANDLE hThread[3];
		CWinThread* pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1);
		CWinThread* pT2=AfxBeginThread((AFX_THREADPROC)threadA,(void*)2);
		CWinThread* pT3=AfxBeginThread((AFX_THREADPROC)threadA,(void*)3);
		hThread[0]=pT1->m_hThread;
		hThread[1]=pT2->m_hThread;
		hThread[2]=pT3->m_hThread;
		//等待线程结束
		WaitForMultipleObjects(3,hThread,TRUE,INFINITE);
		DeleteCriticalSection(&criCounter);
		printf("\nover\n");
	}

	return nRetCode;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -