江湖告急!!win7线程同步问题``````

soswaidao 2011-06-15 07:23:35
最近程序老出问题,查来查去终于找了罪魁祸首,原来是同步出了问题写了个程序测试了下,不测不知道,一测吓一跳.

CRITICAL_SECTION CriticalSection;
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&CriticalSection);

EnterCriticalSection(&CriticalSection);
MessageBox(0,"进入临界区","enter",MB_OK);
//LeaveCriticalSection(&CriticalSection);
EnterCriticalSection(&CriticalSection);

MessageBox(0,"我不会弹出...不会的,不会的....不可能的...","不可思议",MB_OK);
DeleteCriticalSection(&CriticalSection);
return 0;
}

调用EnterCriticalSection后我并没有leave,又再次调用EnterCriticalSection,
这样应该死锁才对,怎么程序就直接执行下去了,弹出了第2个messagebox,并没有在那里等待.以前一直好好的,直到最近程序出现问题,才找到这问题,以前都是能锁住的,现在怎么没用了.
平台 vs2010+Win7
...全文
399 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
soswaidao 2011-06-15
  • 打赏
  • 举报
回复
刚用event测试了下,能卡住,多谢各位解答,问题解决了
kyotrue 2011-06-15
  • 打赏
  • 举报
回复
你想让他怎么卡住?
让你调用CreateThread的线程卡住,然后用CreateThread出来的那个线程解锁?
用Event嘛
soswaidao 2011-06-15
  • 打赏
  • 举报
回复
要怎样才能使他卡住呢,我有个线程,想从线程中释放这个控制,
case FD_READ: // 套接字接受到对方发送过来的数据包
{
// 接受真正的网络数据
shared_ptr<char> szText(new char[1024*8]);
int len = ::recv(s, szText.get(), 1024*8, 0);

PARMDATA data1;
data1.pData = szText;
data1.DataLen = len;
data1.socketVar = s;
//EnterCriticalSection(&g_CrSection);

CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)RecvDoThread,&data1,NULL,NULL);
MessageBox("hello");

//EnterCriticalSection(&g_CrSection);
//LeaveCriticalSection(&g_CrSection);

}
break;
a220315410 2011-06-15
  • 打赏
  • 举报
回复
学习了,虽然的确知道这个临界区就是这样设计的,但是用的时候,很容易像楼主一样忘记呢。
kyotrue 2011-06-15
  • 打赏
  • 举报
回复
这个跟Win7无关,临界区只是实现线程互斥的,占有了临界区的线程可以多次进入临界区,有计数的,不会卡住的,但是也需要调用同样多次的LeaveCriticalSetion,否则其他线程进不了
Eleven 2011-06-15
  • 打赏
  • 举报
回复
After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.

15,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧