[关闭]
@JunQiu 2018-11-27T09:33:33.000000Z 字数 1422 阅读 1075

Python 多线程

language_py summary_2018/11


1、多线程

2、创建线程

  1. import threading
  2. # import time
  3. def thread_test():
  4. # time.sleep(7) //如果创建多个线程几乎会同时完成,释放i/o
  5. print(f"{threading.current_thread().name}")
  6. # 主线程
  7. print(f"{threading.current_thread().name}")
  8. # 子线程
  9. t = threading.Thread(target=thread_test, name='test thread')
  10. t.start()

3、线程通信 & lock

  1. // example:理论上最后输出的num=10,但是由于线程的切换,导致num输出了错误的结果
  2. import threading
  3. num = 10
  4. def test_unlock(n):
  5. global num
  6. num -= n
  7. num += n
  8. def test():
  9. for x in range(100000):
  10. test_unlock(x)
  11. print(num)
  12. t1 = threading.Thread(target=test)
  13. t2 = threading.Thread(target=test)
  14. t1.start()
  15. t2.start()
  16. t1.join()
  17. t2.join()
  18. print(num)
  19. //输出
  20. 10
  21. -17531
  22. // 因此需要保证一个线程对test_unlock执行过程的完整持有,不会被其它线程中途切入,引入threading.Lock()实现
  23. lock = threading.Lock()
  24. # 正确输出结果
  25. def test():
  26. for x in range(100000):
  27. lock.acquire()
  28. test_unlock(x)
  29. lock.release()

4、GIL锁(Global Interpreter Lock)

  1. // 其它
  2. 1GIL并不是python的特性,而是在CPython编译器上引入的特性。
  3. 2GIL可以看作在进程上的全局锁,为了保证多线程中数据的一致性、完整性问题而引入,保证了线程安全。虽然发现了缺陷,但由于依赖GIL之上的功能太多,所有无法简单移除,虽然官方也在尝试进行改进,但还是比较困难。

5、参考文献

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注