如何处理python中的多个线程?

时间:2018-06-09 01:55:28

标签: python multithreading python-3.x sockets message-queue

我正在使用python测试本地服务器和客户端中的线程。我看了很多例子,但他们以完全不同的方式做到了。我是新人,所以我很难理解它。我的代码问题是,当客户端只发送一条消息时,它工作正常;但是,当客户端发送多条消息(使用for-loop)或多个客户端同时发送消息时,服务器会同时接收所有消息,因此它会以错误的方式打印。这是我的代码的一部分:

用于服务器部分:

def insert_projects(project):
    ...

class ThreadNum(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            msg = self.queue.get()
            print("Got message", end=' ')
            insert_projects(msg)
            time.sleep(1)
            self.queue.task_done()
def main():
    server_address = (server_ip, server_port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(server_address)
    print('socket binded to %s port %s' % server_address)
    sock.listen(5)
    print('socket is listening')
    connection, client_address = sock.accept()
    for i in range(100):
        t = ThreadNum(queue)
        t.setDaemon(True)
        t.start()
    while True:
        data = connection.recv(buf_size)
        data = ast.literal_eval(data.decode('utf-8'))
        print('received ', data)
        str_message = str(data)
        queue.put(str_message)
        queue.join()

函数insert_projects只是为了向mysql数据库插入消息信息,所以它不会影响这个部分。

客户部分

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (server_ip, server_port)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)

try:
# Input data
for i in range(3):
    message = {"Project":"KF#2","Type":"GW1","Qty":"12345678","DATE":"18/05/24","TIME":"14:16:20"}
    # Send data
    print('sending ', message)
    sock.sendall(str(message).encode('utf-8'))

finally:
    print('closing socket')
    sock.close()

有人可以帮助我如何将收到的消息逐个划分成​​队列吗?

0 个答案:

没有答案