thread5_GIL.py 920 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. # View more python learning tutorial on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. import threading
  5. from queue import Queue
  6. import copy
  7. import time
  8. def job(l, q):
  9. res = sum(l)
  10. q.put(res)
  11. def multithreading(l):
  12. q = Queue()
  13. threads = []
  14. for i in range(4):
  15. t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
  16. t.start()
  17. threads.append(t)
  18. [t.join() for t in threads]
  19. total = 0
  20. for _ in range(4):
  21. total += q.get()
  22. print(total)
  23. def normal(l):
  24. total = sum(l)
  25. print(total)
  26. if __name__ == '__main__':
  27. l = list(range(1000000))
  28. s_t = time.time()
  29. normal(l*4)
  30. print('normal: ',time.time()-s_t)
  31. s_t = time.time()
  32. multithreading(l)
  33. print('multithreading: ', time.time()-s_t)