美文网首页
python 多线程 共同写一个变量

python 多线程 共同写一个变量

作者: 橙姜 | 来源:发表于2018-02-07 14:05 被阅读0次

    https://docs.python.org/3/library/threading.html#threading.Condition

    https://stackoverflow.com/questions/17774768/python-creating-a-shared-variable-between-threads

    import threading
    import time
    c = threading.Condition()
    flag = 0 #shared between Thread_A and Thread_B
    val = 20

    class Thread_A(threading.Thread):
    def init(self, name):
    threading.Thread.init(self)
    self.name = name

    def run(self):
        global flag
        global val     #made global here
        while True:
            c.acquire()
            if flag == 0:
                print "A: val=" + str(val)
                time.sleep(0.1)
                flag = 1
                val = 30
                c.notify_all()
            else:
                c.wait()
            c.release()
    

    class Thread_B(threading.Thread):
    def init(self, name):
    threading.Thread.init(self)
    self.name = name

    def run(self):
        global flag
        global val    #made global here
        while True:
            c.acquire()
            if flag == 1:
                print "B: val=" + str(val)
                time.sleep(0.5)
                flag = 0
                val = 20
                c.notify_all()
            else:
                c.wait()
            c.release()
    

    a = Thread_A("myThread_name_A")
    b = Thread_B("myThread_name_B")

    b.start()
    a.start()

    a.join()
    b.join()

    相关文章

      网友评论

          本文标题:python 多线程 共同写一个变量

          本文链接:https://www.haomeiwen.com/subject/iogozxtx.html