用多執行緒,實現併發,TCP

pythoner_wl發表於2020-04-25

首先,開啟新的執行緒,是不會新開闢記憶體空間的,即,子執行緒和主執行緒 都在同一個程式裡,也就是主程式裡,用os.pid(),os.ppid()

伺服器:
方式一:Thread例項化

def task(conn, addr):
    # print(os.getpid())
    # print(os.getppid())
    # print(current_thread().name)
    # print(current_thread().is_alive())
    # print(active_count())
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                print('連線已斷開')
                break
            print('收到客戶端%s第一條資訊%s' % (conn, addr))
            print('資訊為:%s' % data.decode('utf-8'))
            conn.send('good'.encode('utf-8'))
        except Exception:
            print('連線已斷開')
            break


#
#
#
if __name__ == '__main__':
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('127.0.0.1', 6666))
    server.listen(5)
    while True:
        conn, addr = server.accept()
        # print(os.getpid())
        # print(os.getppid())
        t1 = Thread(target=task, args=(conn, addr))
        t2 = Thread(target=task, args=(conn, addr))
        t1.start()
        t2.start()

服務端:
方拾二:自定義子類,繼承Thread,__init__可以新增新的屬性,要在run裡,實現你的一些函式,把引數傳進去。

def task(conn, addr):
    # print(os.getpid())
    # print(os.getppid())
    # print(current_thread().name)
    # print(current_thread().is_alive())
    # print(active_count())
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                print('連線已斷開')
                break
            print('收到客戶端%s第一條資訊%s' % (conn, addr))
            print('資訊為:%s' % data.decode('utf-8'))
            conn.send('good'.encode('utf-8'))
        except Exception:
            print('連線已斷開')
            break

class Mythread(Thread):
    def __init__(self, task, args):
        super().__init__(target=task, args=args)

    def run(self):
        task(conn, addr)


if __name__ == '__main__':
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('127.0.0.1', 6666))
    server.listen(5)
    while True:
        conn, addr = server.accept()
        t1 = Mythread(task=task, args=(conn, addr))
        t1.start()

相關文章