@JunQiu
2018-11-27T09:33:33.000000Z
字数 1422
阅读 1506
language_py summary_2018/11
import threading# import timedef thread_test():# time.sleep(7) //如果创建多个线程几乎会同时完成,释放i/oprint(f"{threading.current_thread().name}")# 主线程print(f"{threading.current_thread().name}")# 子线程t = threading.Thread(target=thread_test, name='test thread')t.start()
// example:理论上最后输出的num=10,但是由于线程的切换,导致num输出了错误的结果import threadingnum = 10def test_unlock(n):global numnum -= nnum += ndef test():for x in range(100000):test_unlock(x)print(num)t1 = threading.Thread(target=test)t2 = threading.Thread(target=test)t1.start()t2.start()t1.join()t2.join()print(num)//输出10-17531// 因此需要保证一个线程对test_unlock执行过程的完整持有,不会被其它线程中途切入,引入threading.Lock()实现lock = threading.Lock()# 正确输出结果def test():for x in range(100000):lock.acquire()test_unlock(x)lock.release()
// 其它1、GIL并不是python的特性,而是在CPython编译器上引入的特性。2、GIL可以看作在进程上的全局锁,为了保证多线程中数据的一致性、完整性问题而引入,保证了线程安全。虽然发现了缺陷,但由于依赖GIL之上的功能太多,所有无法简单移除,虽然官方也在尝试进行改进,但还是比较困难。
