想知道如果需要访问多个线程(读/写/获取大小),是否需要锁定Python列表?在Mac上使用Python2.7。在
我写了一个原型来添加一个锁来保护列表。不确定是否有必要,或者代码中是否存在任何问题(性能和功能方面)?谢谢。在
顺便说一句,我在Python字典和deque上有同样的问题,关于在多线程环境中是否需要锁来保护它。谢谢。在
import threading
import time
import random
class checkStatus:
def __init__(self):
self.message = []
self.lock = threading.Lock()
def checkInStatus(self, msg):
self.lock.acquire()
self.message.append(msg)
self.lock.release()
def checkOutStatus(self):
self.lock.acquire()
if len(self.message) > 0:
msg = self.message.pop(0)
else:
msg = 'Queue empty'
self.lock.release()
return msg
def checkMessageStatus(self):
self.lock.acquire()
size = len(self.message)
self.lock.release()
return size
messageQueue = checkStatus()
class myThread (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
global messageQueue
while True:
time.sleep(1+5*random.random())
print "%s: %s : %s" % (self.name, time.ctime(time.time()), messageQueue.checkMessageStatus())
time.sleep(1 + 5 * random.random())
msg = time.ctime(time.time()) + ' ' + self.name
print "%s: %s : check in message, %s" % (self.name, time.ctime(time.time()), msg)
messageQueue.checkInStatus(msg)
time.sleep(1 + 5 * random.random())
print "%s: %s : check out message, %s" % (self.name, time.ctime(time.time()), messageQueue.checkOutStatus())
if __name__ == "__main__":
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1")
thread2 = myThread(2, "Thread-2")
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
输出
^{pr2}$
{{a1>其他的原子方法都是简单的,因为它们不需要一个简单的原子方法来执行。如果没有checkOutStatus中的锁,可能会出现if语句的计算结果为True,但在使用
self.message.pop(0)
检索消息之前,会立即发生线程切换。如果第二个线程随后删除消息,当第一个线程继续时,它将尝试从空列表中弹出。如果将函数重写如下:它也是线程安全的,因为唯一的操作是原子的。在这种情况下,你可以放弃所有的锁定代码。在
相关问题 更多 >
编程相关推荐