Python:套接字和线程? [英] Python: Socket and threads?

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

问题描述

我有一个设计问题:

我有两个线程,一个心跳/控制线程和一个消息处理程序线程.

I have two threads, a heartbeat/control thread and a messagehandler thread.

两个都共享同一个套接字,但是messageHandler线程仅发送消息而从未接收.心跳线程发送和接收(接收消息并对心跳做出反应).

Both are sharing the same socket, however the messageHandler thread only sends out messages and never receives. The heartbeat thread sends and receives (receives messages and reacts on heartbeats).

问题是我不确定这是否安全.我本人没有实现查看套接字是否正在使用的机制. 那么通过python共享套接字会自动安全吗?

The problem is I'm not sure if this is safe. There is no mechanism, I myself, implemented to see if the socket is being used. So is sharing a socket over python automatically thread safe or not?

如果不是这样,我将它们放在单独的线程中的原因是,心跳比消息处理更重要.这意味着,如果它被消息淹没,它仍然需要进行心跳检测.因此,如果我必须实现一个螺栓,是否可以优先处理我的心跳/控制线程是否需要发送心跳?

Also if it's not, the reason I put them in a separate thread is because the heartbeat is more important than the message handling. This means that if it gets flooded with messages, it still needs to do a heartbeat. So if I have to implement a bolt, is there away I can prioritize if my heartbeat/control thread needs to send a heartbeat?

推荐答案

不幸的是,多线程共享的套接字不是线程安全的.考虑一下缓冲区两个线程在没有锁的情况下进行操作.

Unfortunately,The socket shared by multi-thread is not thread safe.Think about buffer two threads operate on with no lock.

通常的实现方式是使用两个套接字,就像ftp一样.cmd套接字和msg套接字.

The normal way to implement is with two socket,just like what ftp does.cmd socket and msg socket.

如果要通过一个套接字实现此功能,则可以将不同类型的消息放入不同的队列中,并使用第三个线程来消耗该队列并通过唯一的套接字发送它们.

If you wanna implement this by one socket,you can put different type msgs into different queues,and with a third thread consumes the queue and send them through the only socket.

通过这种方式,您可以优先于数据味精控制心跳味精.

In this way,you can control heartbeat msg priory to data msg.

这篇关于Python:套接字和线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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