多线程在python中作用不大 GIL的原因

添加线程

本节我们来学习threading模块的一些基本操作,如获取线程数,添加线程等。首先别忘了导入模块:

  1. import threading

获取已激活的线程数

  1. threading.active_count()
  2. # 2

查看所有线程信息

  1. threading.enumerate()
  2. # [<_MainThread(MainThread, started 140736011932608)>, <Thread(SockThread, started daemon 123145376751616)>]

输出的结果是一个<_MainThread(...)>带多个``。

查看现在正在运行的线程

  1. threading.current_thread()
  2. # <_MainThread(MainThread, started 140736011932608)>

添加线程,threading.Thread()接收参数target代表这个线程要完成的任务,需自行定义

  1. def thread_job():
  2. print('This is a thread of %s' % threading.current_thread())
  3. def main():
  4. thread = threading.Thread(target=thread_job,) # 定义线程
  5. thread.start() # 让线程开始工作
  6. if __name__ == '__main__':
  7. main()

join()

加入thread.join()之后会等待这一步进行完才进行下一步

储存进程结果 Queue

  1. import threading
  2. import time
  3. from queue import Queue
  4. def job(l,q):
  5. for i in range (len(l)):
  6. l[i] = l[i]**2
  7. q.put(l)
  8. def multithreading():
  9. q =Queue()
  10. threads = []
  11. data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
  12. for i in range(4):
  13. t = threading.Thread(target=job,args=(data[i],q))
  14. t.start()
  15. threads.append(t)
  16. for thread in threads:
  17. thread.join()
  18. results = []
  19. for _ in range(4):
  20. results.append(q.get())
  21. print(results)
  22. if __name___=='__main__':
  23. multithreading()

使用 Lock 的情况

lock在不同线程使用同一共享内存时,能够确保线程之间互不影响,使用lock的方法是, 在每个线程执行运算修改共享内存之前,执行lock.acquire()将共享内存上锁, 确保当前线程执行时,内存不会被其他线程访问,执行运算完毕后,使用lock.release()将锁打开, 保证其他的线程可以使用该共享内存。