询问者
C++ concurrency::wait() 多线程下吃内存的问题

问题
-
多线程情况下,使用concurrency::wait() 会发生内存暴涨,测试代码如下
#include "stdafx.h"
#include "concrt.h"
#include <windows.h>
#include <process.h>
using concurrency::event;
static event s_iEvent;
HANDLE s_hThread1(NULL);
HANDLE s_hThread2(NULL);
static unsigned _stdcall testThread(void* pParam)
{
while (true)
{
s_iEvent.set();
s_iEvent.wait(200);
s_iEvent.reset();
}
return 0;
}
int main()
{
s_hThread1 = (HANDLE)_beginthreadex(NULL, 0, &testThread, NULL, 0, NULL);
s_hThread2 = (HANDLE)_beginthreadex(NULL, 0, &testThread, NULL, 0, NULL);
while (1);
return 0;
}
全部回复
-
Hi ObserverZ,
感谢在MSDN论坛发帖。
根据MSDN文档中的描述,如果调度器其他不和调度器合作的任务,则wait()等待时间可能是无限期的。所以在多线程环境中使用wait()函数时,不应使用你提供的代码形式。而是类似下列代码的形式。
while(不满足条件)
{
wait( );
…
}
并且尽量保证在wait()循环退出之前,条件会得到满足。
另外,在多线程中,全局变量和静态变量都是需要尽量避免的。可以使用互斥锁等安全机制保护共享资源。
Best Regards,
Sera Yu
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.