发送命令以运行python进度

时间:2014-04-15 08:46:22

标签: python python-3.x tcp tcpserver

我想通过TCP服务器从服务器与客户端进行通信。关于这个的问题是我将从不同的线程向客户端发送字节(例如,通常的方法)。当有人从网上调用python脚本时。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

您可以为连接客户端时创建的线程定义成员变量。然后使用锁写入此变量。所有线程都将共享此变量:

import threading

class ConnectedClients(threading.Thread):

    used_ressources = list()
    used_ressources_lock = threading.Lock()

    def run(self, ressource_to_get):
        if ressource_to_get in used_ressources:
            raise Exception('Already used ressource:' + repr(ressource_to_get))
        else:
            can_access = self.used_ressources_lock.acquire(blocking=True, timeout=5)
            if can_access:
                self.used_ressources.append(ressource_to_get)
                self.used_ressources_lock.release()
                # Do something...
                # You will have to acquire lock and remove ressource from
                # the list when you're done with it.
            else:
                raise Exception("Cannot acquire lock")

您正在寻找这样的东西吗?

相关问题