并发编程之线程、线程定时器、进程池、线程池(更新中....)

线程queue用法

  • import queue
  • q = queue.Queue() 队列 先进先出

  • q = queue.LifoQueue() #堆栈 先进后出
  • q = queue.PriorityQueue() # 可以根据优先级取数据

线程定时器

  • 导入
    • from threading import Thread,Timer
  • 使用
    • t = Timer(4,task) #过了4秒开启了一个线程

socket 多线程

  • 服务端

    • import socket
      from threading import Thread
      def task(conn):
          while True:
              try:
                  msg = conn.recv(1024)
                  if len(msg) == 0:break
                  conn.send(msg.upper())
              except Exception:
                  print("客户端关闭了一个链接")
                  break        
      def run():
          while True:
              s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
              s.bind(('127.0.0.1',8020))
              s.listen(5)
      
              while True:
                  conn,addr = s.accept()
                  t = Thread(target=task,args=(conn,))
                  t.start()         
      if __name__ == '__main__':
          run()
      
  • 客户端

    • import socket
      from threading import Thread,currentThread
      def run():
          s = socket.socket()
          s.connect(('127.0.0.1',8020))
          while True:
              msg = f"{currentThread().name}"
              if len(msg) == 0:continue
              s.send(msg.encode('utf-8'))
              Msg = s.recv(1024)
              print(Msg.decode())
      if __name__ == '__main__':
          for i in range(20):
              t = Thread(target=run)
              t.start()

进程池与线程池

  • 进程池代码

    • from concurrent.futures import ProcessPoolExecutor
      from multiprocessing import current_process
      import time
      """ 进程池 """
      def task(i):
          print(f"线程:{current_process().name} 正在执行任务:{i}")
          time.sleep(1)
          return i ** 2
      
      
      def parse(res):
          print(res.result())
      if __name__ == '__main__':
          pool = ProcessPoolExecutor(4)  #定义线程池大小
          for i in range(20):
              res = pool.submit(task,i)
              res.add_done_callback(parse)
  • 线程池代码

    • from concurrent.futures import ThreadPoolExecutor
      from threading import currentThread
      import time
      """ 线程池 """
      def task(i):
      # currentThread().name 代表取出线程名字 名字由初始函数构造,可自行更改
          f"{currentThread().name} 在执行任务{i}"
          time.sleep(1)
          return i ** 2
      if __name__ == '__main__':
      # pool = ThreadPoolExecutor(4) 定义线程池大小
          pool = ThreadPoolExecutor(4)
          fu_list = []
          for i in range(20):
      #future = pool.submit(task,i) 提交执行函数和参数到线程池
              future = pool.submit(task, i)
              fu_list.append(future)
      #pool.shutdown() # 关闭了池的入口,会等待所有的任务执行完,结束阻塞
          pool.shutdown()
          for fu in fu_list:
      #print(fu.result()) 打印返回值
              print(fu.result())

你可能感兴趣的:(并发编程之线程、线程定时器、进程池、线程池(更新中....))