我是python的新手,并试图理解threading.Lock的概念。以下是我输入的示例
#!/usr/bin/python
import threading
import Queue
class suleman(threading.Thread):
def __init__(self,q,lock):
threading.Thread.__init__(self)
self.lock=lock
self.queue=q
def run(self):
self.lock.acquire()
file=open('sul.txt','a')
q=self.queue.get()
print q
q=str(q)
file.write(q)
self.lock.release()
self.queue.task_done()
queue=Queue.Queue()
lock=threading.Lock
for i in range(0,10):
z1=suleman(queue,lock)
z2=suleman(queue,lock)
z1.setDaemon(True)
z2.setDaemon(True)
z1.start()
z2.start()
for i in range(0,10):
queue.put(i)
queue.join()
它给出了以下错误:
File "lock.py", line 11, in run
self.lock.acquire()
AttributeError:'builtin_function_or_method'对象没有属性'acquire'
任何帮助都将受到高度赞赏!
答案 0 :(得分:2)
Threading.Lock不是锁,它会创建一个锁:
In [1]: import threading
In [2]: threading.Lock
Out[2]: <function thread.allocate_lock>
In [3]: threading.Lock()
Out[3]: <thread.lock at 0x7f9ea666def0>
因此,您需要将lock=threading.Lock
更改为lock=threading.Lock()
。