How can I use threading in Python?

前端 未结 19 2662
迷失自我
迷失自我 2020-11-21 04:54

I am trying to understand threading in Python. I\'ve looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I\'m having trou

19条回答
  •  渐次进展
    2020-11-21 05:10

    For me, the perfect example for threading is monitoring asynchronous events. Look at this code.

    # thread_test.py
    import threading
    import time
    
    class Monitor(threading.Thread):
        def __init__(self, mon):
            threading.Thread.__init__(self)
            self.mon = mon
    
        def run(self):
            while True:
                if self.mon[0] == 2:
                    print "Mon = 2"
                    self.mon[0] = 3;
    

    You can play with this code by opening an IPython session and doing something like:

    >>> from thread_test import Monitor
    >>> a = [0]
    >>> mon = Monitor(a)
    >>> mon.start()
    >>> a[0] = 2
    Mon = 2
    >>>a[0] = 2
    Mon = 2
    

    Wait a few minutes

    >>> a[0] = 2
    Mon = 2
    

提交回复
热议问题