2017-08-22 8 views
0

私は新しいスレッドPythonのマルチスレッド

thread1 = threading.Thread(target=loop_logic,args=(client1,)) 
thread2 = threading.Thread(target=loop_logic,args=(client2,)) 

に新しいクライアントをスクリプト実行しているとTrue条件

は私のスクリプトがserver.py

あるとしましょうながら、彼らは常に持つに実行されています

client.pyclient.py私はclient.pyを実行するときに実行中にserver.pyに新しいスレッドを追加したいと思っています。

thread3 = threading.Thread(target=loop_logic,args=(client3,)) 

など。 これを行うにはどのような方法がありますか?

+0

パイプやソケットのようなスクリプト間のコミュニケーションが必要です。 – Artyer

+0

私は今日のソケット、クライアントから新しいスレッドを実行するための私に与えることができる任意のシンプルなコードについて学びますか?ありがとう – WillyRL

答えて

0

クライアントとサーバーの両方のクラスを作成し、サーバーへの参照をそれぞれの新しいクライアントに渡し、新しいクライアントを作成するための関数をサーバークラスに追加することができます。ここでは非常に基本的な例この例logic_loop

import threading 

class Server(object): 
    def __init__(self): 
     self.chilren = [] 
     self.threads = [] 
    def NewChild(self, client_info): 
     child = Client(self, client_info) # self is a reference to the current server instance 
     child_thread = threading.thread(target=child.run, args=(,)) 
     self.children.append(child) 
     self.threads.append(child_thread) 
     child_thread.start() 
    def run(self): 
     pass 
     # Whatever server code should go here 

class Client(object): 
    def __init__(self, parent, info): # info is a stand-in for arguments 
     self.parent = parent 
     self.info = info 
    def run(self): 
     self.parent.NewChild(other_info) 
     # Any other processing too 

Client.run方法によって置き換えられています。その関数で行われる処理はrunで行われ、引数はすべてinfo引数としてクラスに渡されます

+0

私は試してみる、ありがとう! – WillyRL

関連する問題