我正在尝试了解Windows上的互斥体,但是在2012年的Visual Studio 2012上,波纹管代码无法正常工作。代码的目的不是检查错误条件,而是检查基本的api用法。 我创建了100个线程,每个线程只有一个任务。增加全局变量testThisVariableIncr。每个线程调用的函数是MyThreadFunction()。
请指导我哪里弄错了。
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include "iostream"
using namespace std;
#define MAX_THREADS 100
#define BUF_SIZE 255
static int testThisVariableIncr;
DWORD WINAPI MyThreadFunction(LPVOID lpParam);
// Each thread will be sent this data structure
typedef struct MyData {
int val1;
int val2;
} MYDATA, *PMYDATA;
// al lhandles are usuly void POINTERS
HANDLE ghMutex;
int _tmain()
{
PMYDATA pDataArray[MAX_THREADS];
DWORD dwThreadIdArray[MAX_THREADS];
HANDLE hThreadArray[MAX_THREADS];
// cretae a mutex but will be used by each thread
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
// Create MAX_THREADS worker threads.
for (int i = 0; i<MAX_THREADS; i++)
{
// CREATE DATA TOR EACH THREAD =============================================
// Allocate memory for thread data.
pDataArray[i] = new MYDATA();
pDataArray[i]->val1 = i;
pDataArray[i]->val2 = i ;
//=============================================
// Create the thread to begin execution on its own.
hThreadArray[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
pDataArray[i], // argument to thread function
0, // use default creation flags
&dwThreadIdArray[i]); // returns the thread identifier
} // End of main thread creation loop.
// Wait until all threads have terminated.something like join of linux
WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
cout << "\n final value is : " << testThisVariableIncr;
// Close all thread handles and free memory allocations.
for (int i = 0; i<MAX_THREADS; i++)
{
CloseHandle(hThreadArray[i]);
if (pDataArray[i] != NULL)
{
delete pDataArray[i];
pDataArray[i] = NULL; // Ensure address is not reused.
}
}
CloseHandle(ghMutex);
getchar();
return 0;
}
DWORD WINAPI MyThreadFunction(LPVOID lpParam)
{
// Cast the parameter to the correct data type.
// The pointer is known to be valid because
// it was checked for NULL before the thread was created.
PMYDATA pDataArray;
pDataArray = (PMYDATA)lpParam;
while (1)
{
DWORD dwWaitResult = WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
if (WAIT_OBJECT_0 == dwWaitResult)
{
testThisVariableIncr++;
ReleaseMutex(ghMutex);
return 0;
}
Sleep(1);
}
return 0;
}
10次运行2-3次我获得97 95等而不是99次预期。