ポートスキャナの[1]マルチスレッド反発
CriticalSectionがなければ、同じ値が出る機会は大きいです.
- #include <iostream>
- #include <stdio.h>
- #include <windows.h>
- #include <string>
-
- int nShareVar = 0;
-
- CRITICAL_SECTION gcs;
-
- class HalfLock
- {
- public:
- HalfLock(CRITICAL_SECTION *gcs)
- {
- m_pSection = gcs;
- }
- ~HalfLock()
- {
- if(m_IsNull == FALSE)
- ::LeaveCriticalSection(m_pSection);
- }
- public:
- void Lock()
- {
- ::EnterCriticalSection(m_pSection);
- m_IsNull = FALSE;
- }
- void UnLock()
- {
- if(m_IsNull == FALSE)
- {
- ::LeaveCriticalSection(m_pSection);
- m_IsNull = TRUE;
- }
- }
- private:
- CRITICAL_SECTION *m_pSection;
- BOOL m_IsNull;
- };
-
-
- DWORD WINAPI RecvThread(LPVOID lp)
- {
- int num = *(DWORD*)lp; //
- char tempBuf[128];
- HalfLock lock(&gcs);
- while(nShareVar < 1000)
- {
- sprintf_s(tempBuf, "Thread %d :: nShareVar = %d
", num, nShareVar);
- std::cout<<tempBuf;
- //EnterCriticalSection(&gcs);
- lock.Lock();
- nShareVar++;
- lock.UnLock();
- //LeaveCriticalSection(&gcs);
- }
- return 0;
- }
-
- int main(void)
- {
- InitializeCriticalSection(&gcs);
- HANDLE Threads[10];
- // Threads
- for(int i=0; i<10; i++)
- {
- Threads[i] = CreateThread(NULL, 0, RecvThread, &i, 0, NULL);
- Sleep(500);
- }
- WaitForMultipleObjects(10, Threads, TRUE, 50000);
- DeleteCriticalSection(&gcs);
- TerminateThread(Threads, 0);
- for(int i=0; i<10; i++)
- {
- CloseHandle(Threads[i]);
- }
- system("pause");
- return 1;
- }