我寫了一個多線程程序,其中三個線程試圖將文本保存到同一個文件。我申請了關鍵部分。而在Windows 7下完美的作品,但在CE 6.0不同步,即,每個線程正試圖在同一時間保存:爲什麼線程同步不起作用?
它現在的作品!感謝大家的幫助!
關鍵部分:
InitializeCriticalSection(&CriticalSection);
// Create worker threads
for(i=0; i < THREADCOUNT; i++)
{
aThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) WriteToFile, NULL, 0, &ThreadID);
if(aThread[i] == NULL)
{
printf("CreateThread error: %d\n", GetLastError());
return 1;
}
}
// Wait for all threads to terminate
for(i=0; i < THREADCOUNT; i++)
{
WaitResult = WaitForSingleObject(aThread[i], INFINITE);
switch(WaitResult)
{
case WAIT_OBJECT_0:
printf("Thread %d has terminated...\n", i);
break;
// Time out
case WAIT_TIMEOUT:
printf("The waiting is timed out...\n");
break;
// Return value is invalid.
default:
printf("Waiting failed, error %d...\n", GetLastError());
ExitProcess(0);
}
}
// Close thread handles
for(i=0; i < THREADCOUNT; i++)
CloseHandle(aThread[i]);
// Release resources used by the critical section object.
DeleteCriticalSection(&CriticalSection);
功能由一個線程調用:
DWORD WINAPI WriteToFile(LPVOID lpParam)
{
// lpParam not used in this example
UNREFERENCED_PARAMETER(lpParam);
DWORD dwCount=1, dwWaitResult;
HANDLE hFile;
char DataBuffer[30];
DWORD dwBytesToWrite;
DWORD dwBytesWritten;
// Request ownership of the critical section.
EnterCriticalSection(&CriticalSection);
// Write to the file
printf("Thread %d writing to file...\n", GetCurrentThreadId());
hFile = CreateFile(TEXT("file.txt"), GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
SetFilePointer(hFile, 0, NULL, FILE_END);
while(dwCount <= 3)
{
sprintf(DataBuffer, "Theard %d writing %d\n", GetCurrentThreadId(), dwCount);
dwBytesToWrite = (DWORD)strlen(DataBuffer);
WriteFile(hFile, DataBuffer, dwBytesToWrite, &dwBytesWritten, NULL);
printf("Theard %d wrote %d successfully.\n", GetCurrentThreadId(), dwCount);
}
}
dwCount++;
}
CloseHandle(hFile);
// Release ownership of the critical section.
LeaveCriticalSection(&CriticalSection);
return TRUE;
}
你怎麼初始化ghCriticalSection?請發佈代碼。謝謝! – hopia
至少匈牙利語是錯誤的,InitializeCriticalSection需要一個指向CRITICAL_SECTION的指針,而不是指向句柄的指針。 –
我有:CRITICAL_SECTION ghCriticalSection; –