An equivalent to Java volatile in Python

后端 未结 2 741
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 21:46

Does Python have the equivalent of the Java volatile concept?

In Java there is a keyword volatile. As far as I know, when we use vola

2条回答
  •  礼貌的吻别
    2021-01-01 22:21

    The keyword "global" is what you are looking for:

    import threading
    
    queue = []
    l = threading.Lock()
    
    def f():
        global queue
        l.acquire()
        queue.append(1)
        l.release()
    
    def g():
        print(queue)
    
    threads = [
        threading.Thread(target=f),
        threading.Thread(target=g)
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    

提交回复
热议问题