如何处理不同线程中的同一套接字? [英] How to handle same socket in different threads?

查看:146
本文介绍了如何处理不同线程中的同一套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理不同线程中的套接字,从而导致运行时失败.请参阅以下代码.

I am trying to handle socket in different threads creating runtime failure. See following code.

void MySocket::Lock()
{
    m_LockCount++;

    if( m_LockCount )
    {
        CSocket::Create( 8080 );
    }
}

void MySocket::Unlock()
{
    m_LockCount--;

    if( !m_LockCount )
    {
        CSocket::Close();
    }
}

我从一个线程调用Lock(),从另一个线程调用Unlock().当它执行CSocket :: Close()时,会给出一个异常.

I am calling Lock() from one thread and Unlock() from other. When it executes CSocket::Close() it gives an exception.

我为此漏洞搜索了Google,并发现了一些原因. 这是因为;一个CSocket对象仅应在单个线程的上下文中使用,因为由CAsyncSocket对象封装的SOCKET句柄存储在每个线程句柄映射中.他们还通过在线程之间共享SOCKET句柄( http://support.microsoft.com/kb /175668 ).但这在我的情况下是不可能的,因为我除了某些通知回调之外,该回调不适用于上述解决方案.有人可以建议一种在线程之间共享CSocket而不影响通知回调的机制吗?

I googled for this bug and got some reasons. This happens because; a CSocket object should be used only in the context of a single thread because the SOCKET handle encapsulated by a CAsyncSocket object is stored in a per-thread handle map. They are also suggesting a solution by sharing SOCKET handles between threads (http://support.microsoft.com/kb/175668). But this is not possible in my case since I am excepting some notification callback which will not work with above solution. Can anybody suggest a mechanism to share CSocket among threads without effecting notification callbacks?

推荐答案

如您所说,如果仅在单个线程的上下文中使用CSocket对象",则不存在在多个线程之间共享CSocket的机制".线程".

If, as you say, "a CSocket object should be used only in the context of a single thread," then there is no "mechanism to share CSocket among threads".

换句话说,一个线程需要拥有CSocket,而其他线程则不能弄乱它.

In other words, one of the threads needs to own the CSocket, and the others can't mess with it.

在这种情况下,解决方案是使用线程间消息传递系统.这样,其他线程之一可以向所有者发送一条消息,说:嘿,伙计,关闭套接字!"

In such cases, the solution is to use an inter-thread messaging system. That way, one of the other threads can send a message to the owner saying, "Hey, buddy, close your socket!"

如何进行消息传递的详细信息完全取决于程序的上下文.

The details of how you would do that messaging depend entirely on the context of your program.

这篇关于如何处理不同线程中的同一套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆