线程同步(for Win32)
#include <windows.h> #include <iostream>
using namespace std;
static int g_n; CRITICAL_SECTION m_cs;
UINT ThreadOne(LPVOID lParam) { EnterCriticalSection(&m_cs);
for (int i = 0; i < 10; i++) { g_n++; cout<<"Thread 1:"<<g_n<<"\n"; } LeaveCriticalSection(&m_cs); return 0; }
UINT ThreadTwo(LPVOID lParam) { EnterCriticalSection(&m_cs);
for (int i = 0; i < 10; i++) { g_n++; cout<<"Thread 2:"<<g_n<<"\n"; } LeaveCriticalSection(&m_cs); return 0; }
int main() { HANDLE hThrd[2]; DWORD IDThread1,IDThread2;
InitializeCriticalSection(&m_cs); hThrd[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadOne, (LPVOID)NULL, 0, &IDThread1); hThrd[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadTwo, (LPVOID)NULL, 0, &IDThread1);
WaitForMultipleObjects(2, hThrd, TRUE, INFINITE); DeleteCriticalSection(&m_cs);
system("pause"); return 0; }
线程同步(for MFC)
#include "win32_mfc.h" #include <afxmt.h> #include <iostream>
#ifdef _DEBUG #define new DEBUG_NEW #endif
// 唯一的应用程序对象
CWinApp theApp;
using namespace std;
CCriticalSection c_s; static int g_C;
UINT ThreadFunction1(LPVOID lParam) { CSingleLock lock(&c_s);
lock.Lock();
for (int i = 0; i < 10; i++) { g_C++; cout<< "Thread 1 : " << g_C << endl; } lock.Unlock(); return 0; }
UINT ThreadFunction2(LPVOID lParam) { CSingleLock lock(&c_s);
lock.Lock();
for (int i = 0; i < 10; i++) { g_C++; cout<< "Thread 2 : " << g_C << endl; } lock.Unlock(); return 0; }
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0;
// 初始化 MFC 并在失败时显示错误 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: 更改错误代码以符合您的需要 _tprintf(_T("错误: MFC 初始化失败\n")); nRetCode = 1; } else { // TODO: 在此处为应用程序的行为编写代码。 CWinThread *Thread[2]; HANDLE hand[2];
Thread[0] = AfxBeginThread(ThreadFunction1, (LPVOID)NULL); Thread[1] = AfxBeginThread(ThreadFunction2, (LPVOID)NULL);
for (int i = 0; i < 2; i++) hand[i] = Thread[i]->m_hThread;
WaitForMultipleObjects(2, hand, TRUE, INFINITE); }
system("pause"); return nRetCode; }
|