单进程+多线程+同步 python 服务器 demo

import socket, threading, queue, time

# 线程
class Work(threading.Thread):
    def __init__(self, pendding_queue=queue.Queue()):
        self.pendding_queue = pendding_queue
        super().__init__()
        self.start()

    def run(self):
        while True:
            try:
                callable, args =self.pendding_queue.get()
            except Exception as e:
                # print('[E]: ' + str(e))
                time.sleep(1)
                continue
            callable(*args)
            print('threads: ' + str(threading.active_count()) + '  pendding_num: ' + str(self.pendding_queue.qsize()))

# 线程池
class ThreadPool():
    def __init__(self, count=10):
        self.count = count
        self.pendding_queue = queue.Queue() # (func, args)
        self.thread_ids = []
        self.create_thread(self.count)

    def add_request(self, target, args):
        self.pendding_queue.put((target, args))

    def create_thread(self, num):
        for i in range(num):
            t = Work(self.pendding_queue)
            self.thread_ids.append(t.ident)

# 处理请求
def handle(conn, addr):
    # print(str(threading.get_ident()) + ' handle connection from addr' + str(addr))
    data = conn.recv(2048)
    # print('recv data:' + str(data, 'utf-8'))
    res = b'back: ' + data
    # time.sleep(1)
    conn.send(res)
    # print('send back data:' + str(res, 'utf-8'))
    conn.close()
    # print('close connection:' + str(conn))

# 启动服务器
def run_server(addr_info):
    sock = socket.socket()
    sock.bind(addr_info)
    sock.listen(5)
    threadpool = ThreadPool(10)
    print('start sever at:' + str(addr_info))
    while True:
        conn, addr = sock.accept()
        threadpool.add_request(handle, (conn, addr))

        # threading.Thread(target=handle, args=(conn, addr)).start()
        # print('current active thread count:' + str(threading.active_count()))


if __name__ == '__main__':
    addr_info = ('localhost', 1111)
    run_server(addr_info)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值