2012-01-22 46 views
4

我寫了一個多線程程序,其中三個線程試圖將文本保存到同一個文件。我申請了關鍵部分。而在Windows 7下完美的作品,但在CE 6.0不同步,即,每個線程正試圖在同一時間保存:爲什麼線程同步不起作用?

它現在的作品!感謝大家的幫助!

Emulator

Kernel tracker

關鍵部分:

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; 
} 
+0

你怎麼初始化ghCriticalSection?請發佈代碼。謝謝! – hopia

+3

至少匈牙利語是錯誤的,InitializeCriticalSection需要一個指向CRITICAL_SECTION的指針,而不是指向句柄的指針。 –

+0

我有:CRITICAL_SECTION ghCriticalSection; –

回答

10

的問題是要傳遞TRUEfWaitAll標誌爲WaitForMultipleObjects。在Windows CE上,不支持:documentation on MSDN表示該標誌必須是FALSEWaitForMultipleObjects因此不會等待,而是返回一個錯誤,但是您不檢查返回碼。因此主線程直通,關閉句柄並刪除臨界區,而「工作者」線程仍在運行。一旦DeleteCriticalSection被調用,臨界區「不再能用於同步」,所以EnterCriticalSection電話可能不再塊,和你結束了你這裏的情況。

在Windows 7上,一切正常,因爲WaitForMultipleObjects呼叫確實等待所有的線程完成。

比使用WaitForMultipleObjects相反,只需使用WaitForSingleObject在一個循環中等待依次在每個線程。

+0

賓果。他沒有檢查他的WaitForMultipleObjects的結果,這會告訴他有錯誤。在CE它可以等待任何,它不能等待所有。 – ctacke

+0

@Anthony:好抓! –