目的

掌握基本的线程语法

实现

1:多线程
2:线程锁
3:线程local
4:控制线程数量
5:凑够线程数量
6:线程等待

代码

1:多线程

  import threading
  import time
  
  
  def run(num):
      print("子线程名字:", threading.current_thread().name)
      print("子线程开始!", threading.current_thread().name)
      time.sleep(5)
      print(num)
      print("子线程结束!", threading.current_thread().name)
  
  
  if __name__ == "__main__":
      print("主线程名字:", threading.current_thread().name)
      print("Main Start!")
      time.sleep(5)
  
      t = threading.Thread(target=run, name=1,args=(520,))
      t.start()
      t.join()
      t1 = threading.Thread(target=run, name=2)
      t1.start()
      t2 = threading.Thread(target=run, name=3)
      t2.start()
      t2.join()
      t3 = threading.Thread(target=run, name=4)
      t3.start()
      t3.join()
      print("Main end!")

2:线程锁

  import threading
  
  
  num = 0
  lock = threading.Lock()
  
  def run(no):
      global num
      for i in range(100000):
          lock.acquire()
          num = num + no
          num = num - no
          lock.release()
  
  if __name__ == "__main__":
      t = threading.Thread(target=run, args=(10,))
      t2 = threading.Thread(target=run, args=(9,))
      t.start()
      t2.start()
      t.join()
      t2.join()
      print("num = ", num)

3:线程local

  import threading
  
  
  num = 0
  local = threading.local()
  
  
  def run(x, n):
      x = x + n
      x = x - n
  
  
  def func(n):
      local.x = num
      for i in range(10000):
          run(local.x, n)
      print("%s=====%d" % (threading.current_thread().name, local.x))
  
  
  if __name__ == "__main__":
      t = threading.Thread(target=func, args=(10,))
      t2 = threading.Thread(target=func, args=(9,))
      t.start()
      t2.start()
      t.join()
      t2.join()
      print("num = ", num)

4:控制线程数量

  import threading
  import time
  
  # 控制线程的数量
  sem = threading.Semaphore(1)
  
  
  def run():
      for i in range(5):
          with sem:
              print("%s----%d" % (threading.current_thread().name, i))
              time.sleep(1)
  
  
  if __name__ == "__main__":
      for i in range(5):
          threading.Thread(target=run).start()

5:凑够线程数量

  import threading
  import time
  
  # 凑够线程数量运行
  bar = threading.Barrier(3)
  
  
  def run():
      print("%s ---> Start"%(threading.current_thread().name))
      time.sleep(2)
      bar.wait()
      print("%s ---> End")
  
  
  if __name__ == "__main__":
      for i in range(14):
          threading.Thread(target=run).start()

6:线程等待

  import threading
  import time
  
  
  bar = threading.Barrier(3)
  
  
  def run():
      print("%s ---> Start" % threading.current_thread().name)
      time.sleep(2)
      bar.wait()
      print("%s ---> End" % threading.current_thread().name)
  
  
  if __name__ == "__main__":
      for i in range(3):
          #等到3秒后运行
          threading.Timer(3, run).start()