gpt4 book ai didi

c++ - 为什么线程同步不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:41 25 4
gpt4 key购买 nike

我写了一个多线程程序,其中三个线程试图将文本保存到同一个文件中。我应用了关键部分。在 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;
}

最佳答案

问题是您将 TRUE 传递给 WaitForMultipleObjectsfWaitAll 标志。在 Windows CE 上,这是不支持的:documentation on MSDN表示此标志必须为 FALSEWaitForMultipleObjects 因此不是等待,而是返回一个错误,但您没有检查返回码。因此,主线程直接通过,关闭句柄并删除关键部分,同时“工作”线程仍在运行。一旦 DeleteCriticalSection 被调用,临界区“不能再用于同步”,所以 EnterCriticalSection 调用可能不再阻塞,你最终会遇到你想要的场景有这里。

在 Windows 7 上,一切正常,因为 WaitForMultipleObjects 调用确实等待所有线程完成。

与其使用 WaitForMultipleObjects,不如在循环中使用 WaitForSingleObject 依次等待每个线程。

关于c++ - 为什么线程同步不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com