读书人

多线程同步关于Semaphore有关问题

发布时间: 2012-01-08 22:48:50 作者: rapoo

多线程同步,关于Semaphore问题
我想让主线程发一个信号唤醒制定的一个线程,然后再由唤醒后的这个线程在发送另外一个信号唤醒另一个线程。

主线程:
A
{
...

h1 = CreateSemaphore( NULL, cMax,cMax, NULL); // unnamed semaphore

printf("signal");
if (hSemaphore == NULL)

{

printf("CreateSemaphore 1 error: %d\n", GetLastError());

}

if (!ReleaseSemaphore(h1,1, NULL) )
{
printf("Release h1 error: %d\n", GetLastError());
}
Sleep(3000);
CloseHandle(h1);
..
}

需要唤醒的第一个线程
B
{
...

DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(h1,0L);

switch (dwWaitResult)
{
case WAIT_OBJECT_0:
{
...
h2 = CreateSemaphore(NULL,cMax,cMax,NULL);
if (h2 == NULL)

{

printf("CreateSemaphore 2 error: %d\n", GetLastError());

}
if (!ReleaseSemaphore(h2,1, NULL) )
{
printf("Release h2 error: %d\n", GetLastError());
}
Sleep(3000);
CloseHandle(h2);
}


...
}

B要唤醒的线程
C
{
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(hRecvSemaphore,0L);

switch (dwWaitResult)
{

case WAIT_OBJECT_0:
{
...

}

break;
}
...


可是为什么Release h2 error?

[解决办法]
代码很乱,思路更乱

信号量最好要统一创建和销毁
如在main中一起创建,main要退出时一起CloseHandle

WaitForSingleObject(hSemaphore,0L);
不要直接设置超时为0,不好控制
也就是一旦创建线程后,该线程就可以直接运行了

其他的,估计还得有个处理数据的线程吧

这样的socket模型效率不高,还不如 一个客户一个线程的模型
[解决办法]

探讨
h2 = CreateSemaphore(NULL,cMax,cMax,NULL);
因为创建信号量时,信号量的计数已经是最大值了,
ReleaseSemaphore(h2,1, NULL)
会增加信号的计数值,所有会不成功

读书人网 >VC/MFC

热点推荐