您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:56 python 字数 2547 阅读 455 来源 www.jb51.cc/python

我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是Lock对象.我的问题是我是否正确使用了锁.如果我从每个线程中设置锁定,该锁定是全局的还是仅特定于该特定线程?基本上,我应该先创建一个Lock并将其引用传递给每个线程,还是可以像在此处一样在线程内设置它:import time from threading import Thread, L

概述

我有线程代码,每个线程需要写入同一个文件.为了防止并发问题,我使用的是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 %s\n' % 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

总结

以上是编程之家为你收集整理的python – 多线程资源访问 – 我在哪里放锁?全部内容,希望文章能够帮你解决python – 多线程资源访问 – 我在哪里放锁?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶