2013-09-05 174 views
0

我正在做一個小客戶端\服務器線程聊天,我有一個問題, 如果其中一方正在接收消息,而輸入一個它的中斷這裏輸入的消息是爲了說明輸入消息中斷時收到一條消息

enter image description here

這裏,圖像是線程代碼:

import threading 
import socket 
class sendTread(threading.Thread): 
    def __init__(self,soc): 
     threading.Thread.__init__(self,name='sender') 
     self.s=soc 
    def run(self): 
     while True: 
      self.s.send(bytes(str(input('>>> ')), 'UTF-8')) 
      print('sent.') 
class recvTread(threading.Thread): 
    def __init__(self,soc): 
     threading.Thread.__init__(self,name='recver') 
     self.s=soc 
    def run(self): 
     while True: 
      data=self.s.recv(1024) 
      print('\nrecv:',str(data)[2:len(str(data))-1],end="\n>>> ")

我明白爲什麼會發生,但我不知道如何解決它,我會很樂意 的一些幫助和建議:)

回答

0

你必須作爲一個併發問題來解決這個問題。在你的情況下,控制檯是一個共享資源,發生的事情是接收者的線程正在使用它,而仍然由發件人「採取」。

您可以添加保護打印報表的鎖,你可以在這裏找到關於它的詳細信息: http://docs.python.org/2/library/threading.html#lock-objects