我面临着多个线程试图向mysql中的同一个表插入数据的情况,**如果没有显式处理它可以吗? ** 恐怕每个线程都在插入,某些线程会被锁定并保持太长时间,然后导致程序崩溃。
基本上我想做的是以下事情:
import threading
import mysql.connector
db = mysql.connector.connect()
cursor = db.cursor()
def update_to_table(data):
sql = "insert into my_db.my_table values(%s)" % data
cursor.excute(sql)
db.commit()
print("update complete!")
for i in range(10):
print("%d -th time..." % i)
data = get_data(i)
t = threading.Thread(target=update_to_table, args=(data,))
t.start()
我是否需要检查其他线程是否正在插入,并保持并等待它们完成等等...
不同i的数据没有重叠,所以我们不需要担心重复key的问题。
经过实验,似乎有些线程会挂起并且没有响应。
最佳答案
根据MySQL Connector/Python Developer Guide ,mysql.connector.threadsafety
属性为1
。
根据PEP 249 ,threadsafety
属性的含义如下:
0 - Threads may not share the module.
1 - Threads may share the module, but not connections.
2 - Threads may share the module and connections.
3 - Threads may share the module, connections and cursors.
Sharing in the above context means that two threads may use a resource without wrapping it using a mutex semaphore to implement resource locking. Note that you cannot always make external resources thread safe by managing access using a mutex: the resource may rely on global variables or other external sources that are beyond your control.
在您的示例中,您有共享单个连接的线程。没有任何显式的资源锁定。这可能会导致线程问题,并且您观察到的症状(线程锁定)并不意外。
此示例中的简单解决方案是为每个线程提供自己的连接对象。
(如果线程数较多,建议使用有并发连接数限制的连接池。数据库服务器会限制一个客户端可以打开的连接数...给老公服务器端资源。此外,在某个点上,您将使用所有特定的服务器端资源;例如 CPU、内存、磁盘带宽、网络带宽。超过该点,添加更多客户端线程不会增加吞吐量.)
关于python - 当多个线程写入 mysql 中的单个表时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644774/