Python多线程中阻塞(join)与锁(Lock)使用误区解析


当前第2页 返回上一页

加锁后的正确代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

# -*- coding: utf-8 -*-

import threading

import time

count = 0

lock = threading.Lock()

class Counter(threading.Thread):

  def __init__(self, name):

    self.thread_name = name

    self.lock = threading.Lock()

    super(Counter, self).__init__(name=name)

  def run(self):

    global count

    global lock

    for i in xrange(100000):

      lock.acquire()

      count = count + 1

      lock.release()

 

 

counters = [Counter('thread:%s' % i) for i in range(5)]

 

for counter in counters:

  counter.start()

 

time.sleep(5)

print 'count=%s' % count

结果:

count=500000

注意锁的全局性

这是一个简单的Python语法问题,但在逻辑复杂时有可能被忽略.
要保证锁对于多个子线程来说是共用的,即不要在Thread的子类内部创建锁.

以下为错误代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

# -*- coding: utf-8 -*-

 

import threading

import time

count = 0

# lock = threading.Lock() # 正确的声明位置

class Counter(threading.Thread):

  def __init__(self, name):

    self.thread_name = name

    self.lock = threading.Lock() # 错误的声明位置

    super(Counter, self).__init__(name=name)

  def run(self):

    global count

    for i in xrange(100000):

      self.lock.acquire()

      count = count + 1

      self.lock.release()

counters = [Counter('thread:%s' % i) for i in range(5)]

 

for counter in counters:

  print counter.thread_name

  counter.start()

 

time.sleep(5)

print 'count=%s' % count

相关推荐:

python线程中同步锁详解

python多线程之事件Event的使用详解

python线程池threadpool的实现

以上就是Python多线程中阻塞(join)与锁(Lock)使用误区解析的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python yield什么意思

Python工资为什么这么高

如何改变 matplotlib 图像大小

Python中的lambda是什么意思

Python实现去除列表中重复元素的方法

如何让Python运行在android上

Python 网络爬虫--关于简单的模拟登录

利用库fractions模块让Python支持分数类型

Python程序的两种运行方式是什么

Python怎么学

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...