两个线程同时访问全局变量 - 图1

    1. import threading
    2. import time
    3. num = 0
    4. def first():
    5. for item in range(100000):
    6. global num
    7. num = num + 1
    8. pass
    9. print(num)
    10. pass
    11. def second():
    12. for item in range(100000):
    13. global num
    14. num = num + 1
    15. pass
    16. print(num)
    17. pass
    18. if __name__ == '__main__':
    19. first_thread = threading.Thread(target=first)
    20. second_thread = threading.Thread(target=second)
    21. first_thread.start()
    22. # 解决方法
    23. first_thread.join()
    24. second_thread.start()