I wrote a multi-threaded program in which three threads try to save text in the same file. I applied a critical section. And under windows 7 it works fine, but in CE 6.0 it does not synchronize, i.e. Each thread tries to simultaneously save:
Now it works !!! Thank you all for your help!


Critical Section:
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);
The function called by the thread:
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; }