有人能告诉我下面的代码中有什么问题,它在python中实现了生产者 - 消费者问题.我使用的是Python 3.4
import threading
from threading import Thread
from collections import deque
import time
maxSize = 4 # maximum size of the queue
q = deque([])
cur = 0 # current value to push into the queue
lk = threading.Lock()
cvP = threading.Condition(lk) # condition object for consumer
cvC = threading.Condition(lk) # condition object for producer
class Producer:
def run(self):
global maxSize, q, cur
while True:
with cvP:
while len(q) >= maxSize:
print( "Queue is full and size …Run Code Online (Sandbox Code Playgroud) PyMySQL,一个用于访问 MySQL 数据库的 python 包,似乎不支持 SELECT ... FOR UPDATE。
在下面的代码中,我使用 SELECT...FOR UPDATE 读取函数 f() 中的 some_table,使用 UPDATE 修改 g() 中的表,并为每个函数生成 50 个线程。
我预计会发生死锁,因为 SELECT...FOR UPDATE 应该阻止 g 生成的线程。但实际上并没有发生僵局。有人可以解释一下为什么吗?
from threading import Thread
import pymysql
def f():
db = pymysql.connect("localhost", "tester","pwd", "testDB")
cur = db.cursor()
sql = "SELECT * FROM some_table FOR UPDATE"
try:
cur.execute(sql)
except:
print("Exception in select")
def g():
db = pymysql.connect("localhost", "tester", "pwd","testDB")
cur = db.cursor()
sql = "UPDATE some_table SET val=20 WHERE id=2"
try:
cur.execute(sql)
db.commit()
except: …Run Code Online (Sandbox Code Playgroud)