假如往以上代码添加 time.sleep函数并给出差异长度的时刻,也许会让这个例子更故意思。无论怎样,这里的题目是,一个线程也许已经挪用update_total函数而且还没有更新完成,此时另一个线程也有也许挪用它而且实行更新内容。按照操纵执行次序的差异,该值也许只被增进一次。
让我们给这个函数添加锁。有两种要领可以实现。第一种方法是行使 try/finally,从而确保锁必定会被开释。下面是示例:
- import threading
-
- total = 0
-
- lock = threading.Lock
- def update_total(amount):
- """
- Updates the total by the given amount
- """
- global total
- lock.acquire
- try:
- total += amount
- finally:
- lock.release
- print (total)
-
- if __name__ == '__main__':
- for i in range(10):
- my_thread = threading.Thread(
- target=update_total, args=(5,))
- my_thread.start
如上,在我们做任那里理赏罚之前就获取锁。然后实行更新 total 的值,最后开释锁并打印出 total 的当前值。究竟上,我们可以行使 Python 的 with语句停止行使 try/finally 这种较为繁琐的语句:
- import threading
-
- total = 0
-
- lock = threading.Lock
-
- def update_total(amount):
- """
- Updates the total by the given amount
- """
- global total
- with lock:
- total += amount
- print (total)
-
- if __name__ == '__main__':
- for i in range(10):
- my_thread = threading.Thread(
- target=update_total, args=(5,))
- my_thread.start
正如你看到的那样,我们不再必要 try/finally作为上下文打点器,而是由with语句作为更换。
虽然你也会碰着要在代码中通过多个线程会见多个函数的环境。当你第一次编写并发代码时,代码也许是这样的:
- import threading
-
- total = 0
-
- lock = threading.Lock
- def do_something:
- lock.acquire
- try:
- print('Lock acquired in the do_something function')
- finally:
- lock.release
- print('Lock released in the do_something function')
- return "Done doing something"
-
- def do_something_else:
- lock.acquire
- try:
- print('Lock acquired in the do_something_else function')
- finally:
- lock.release
- print('Lock released in the do_something_else function')
- return "Finished something else"
-
- if __name__ == '__main__':
- result_one = do_something
- result_two = do_something_else
这样的代码在上面的环境下可以或许正常事变,但假设你有多个线程都挪用这两个函数呢。当一个线程正在运行这两个函数,然后其它一个线程也也许会修改这些数据,最后获得的就是不正确的功效。题目是,你乃至也许没有顿时意识到功效错了。有什么办理步伐呢?让我们试着找出谜底。
凡是起首想到的就是在挪用这两个函数的处所上锁。让我们试着修改上面的例子,修改成如下所示:
- import threading
-
- total = 0
-
- lock = threading.RLock
- def do_something:
-
- with lock:
- print('Lock acquired in the do_something function')
- print('Lock released in the do_something function')
- return "Done doing something"
-
-
- def do_something_else:
- with lock:
- print('Lock acquired in the do_something_else function')
- print('Lock released in the do_something_else function')
- return "Finished something else"
-
- def main:
- with lock:
- result_one = do_something
- result_two = do_something_else
- print (result_one)
- print (result_two)
-
- if __name__ == '__main__':
- main
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|