suspend造成死锁的例子和原因分析 http://blog.csdn.net/magictong/article/details/4161571
2015-12-05 12:47
751 查看
suspend造成死锁的例子和原因分析
标签: 多线程apiaccessnull2009-05-08 18:02 1496人阅读 评论(0) 收藏 举报
分类:
C++ Win32(93)
版权声明:本文为博主原创文章,未经博主允许不得转载。
今天loris分享了一个关于使用suspend造成死锁的例子,部分代码如下:
[cpp] view
plaincopy
UINT AFX_CDECL ThreadTest(LPVOID pvParam)
{
while (TRUE)
{
HMODULE hHandle = ::LoadLibrary("Common.dll");
if (hHandle)
{
void *pFun = (void *)::GetProcAddress(hHandle, "doSomething");
::FreeLibrary(hHandle);
}
::Sleep(10);
}
}
void CTESTWIN2Dlg::OnOK()
{
CWinThread *pThread = AfxBeginThread(ThreadTest, (LPVOID)this,
0, 0,
CREATE_SUSPENDED);
::DuplicateHandle(::GetCurrentProcess(), pThread->m_hThread,
::GetCurrentProcess(), &m_hThread,
0, FALSE, DUPLICATE_SAME_ACCESS);
pThread->ResumeThread();
m_bIsRun = TRUE;
SetTimer(10, 10, NULL);
}
void CTESTWIN2Dlg::OnTimer(UINT nIDEvent)
{
if (m_bIsRun)
{
::SuspendThread(m_hThread);
m_bIsRun = FALSE;
HMODULE hHandle = ::LoadLibrary("TSVul.dat");
if (hHandle)
{
void *pFun = (void *)::GetProcAddress(hHandle, "MyDoSome");
::FreeLibrary(hHandle);
}
}
else
{
::ResumeThread(m_hThread);
m_bIsRun = TRUE;
}
CDialog::OnTimer(nIDEvent);
}
win32下的API基本都是线程安全的,因此API里面有很多线程同步的地方,LoadLibrary里面有一个临界区,线程函数在执行到LoadLibrary里面之后,如果刚好走到LoadLibrary的临界区里面,此时主线程的ontimer触发,将该线程挂起,ontimer继续执行,运行到LoadLibrary后,由于线程中LoadLibrary还没有从临界区出来,此时就造成主线程ontimer里面的LoadLibrary无限等待,主线程挂起。
因此不建议用suspend暂停线程,MSDN也有说明,suspend最好只在debug里面使用。
那怎么使线程挂起呢?可以使用事件等方式,用wait族函数来暂停线程。
【END】
相关文章推荐
- 线程天敌TerminateThread与SuspendThread http://blog.csdn.net/magictong/article/details/6304439
- 265. Paint House II
- WaitForTargetFPS
- UVa253 - Cube painting
- Installation error:INSTALL_FAILED_VERSION_DOWNGRADE
- [LeetCode]99. Container with Most Water最大容积
- CreateThread和_beginthread区别及使用http://blog.csdn.net/wxq1987525/article/details/6620210
- HDU 2674:N!Again【数学】
- 内存泄漏 http://baike.baidu.com/link?url=xs_CTQcDnYkB4fXPOC0-1nAS666wXdUtiUxmP9udmWq4rYFOq4Ij2CElO-iVAjY
- Failed to open/create the internal network Vagrant on Windows10
- maven项目配置Project Facets时further configuration available不出来问题
- wait()和sleep()的区别
- 4-4 Cube Painting
- 你眼中的async/await是什么样的?
- UltraISO 9.6.5.3237
- Daily Scrum - 12/04
- hdoj1032The Snail
- MHA自动Failover过程解析
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-t
- 请求的报的一般错误:One or more post-processing actions failed. Consult the OPP service log for details.