加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 多线程资源访问 – 我在哪里放锁?

发布时间:2020-12-16 22:01:30 所属栏目:Python 来源:网络整理
导读:我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是Lock对象. 我的问题是我是否正确使用了锁.如果我从每个线程中设置锁定,该锁定是全局的还是仅特定于该特定线程? 基本上,我应该先创建一个Lock并将其引用传递给每个线程,还是可以像在此

我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是Lock对象.

我的问题是我是否正确使用了锁.如果我从每个线程中设置锁定,该锁定是全局的还是仅特定于该特定线程?

基本上,我应该先创建一个Lock并将其引用传递给每个线程,还是可以像在此处一样在线程内设置它:

import time
from threading import Thread,Lock

def main():
    for i in range(20):
        agent = Agent(i)
        agent.start()

class Agent(Thread):
    def __init__(self,thread_num):
        Thread.__init__(self)
        self.thread_num = thread_num

    def run(self):
        while True:
            print 'hello from thread %s' % self.thread_num
            self.write_result()   

    def write_result(self):
        lock = Lock()
        lock.acquire()
        try:
            f = open('foo.txt','a')
            f.write('hello from thread %sn' % self.thread_num)
            f.flush()
            f.close()
        finally:
            lock.release()

if __name__ == '__main__':
    main()
最佳答案
在方法外创建锁.

class Agent(Thread):
    mylock = Lock()
    def write_result(self):
        self.mylock.acquire()
        try:
            ...
        finally:
            self.mylock.release()

或者如果使用python> = 2.5:

class Agent(Thread):
    mylock = Lock()
    def write_result(self):
        with self.mylock:
            ...

要在python 2.5中使用它,您必须从以后导入语句:

from __future__ import with_statement

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读