为什么在多线程中传递队列和数据库连接作为参数?

2024-09-29 17:20:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读multi-threading priority queuehere。在这里我不明白为什么workQueue作为参数传递 对于类myThread中的self method,我们可以直接使用workQueue,而不是 使用self.q。所以我写的时候没有用它,但后来我试着用同样的方法连接到 我打开了一个公共数据库连接并允许每个线程使用它。但它不起作用(我的更新并没有反映在数据库中)。我以为线程是先发制人的 他们不可能保持连接来执行查询。但是我给每个线程一个DB连接,我最初把它传递给self方法。在

基本上,我实现了this。令我惊讶的是,这起作用了。这和我做的有什么不同?在


Tags: 方法self数据库dbthis线程multimethod
2条回答

根据the documentation

The MySQL protocol can not handle multiple threads using the same connection at once.

这就是为什么它不起作用,你不能在线程之间共享一个数据库连接(至少对于MySQL是这样)。在

链接到的示例是为每个线程创建连接:

for thread in range(threads):
    try:
        connections.append(MySQLdb.connect(host=mysql_host, user=mysql_user, passwd=mysql_pass, db=mysql_db, port=mysql_port))

in this I don't understand why workQueue is passed as parameter to the self method in class myThread we could have directly used workQueue instead of using self.q

在这个特定的例子中,您可以只引用全局workQueue变量。 但这并不是一个非常普遍的方法,全球变量往往会造成混乱。如果希望对象能够为不同的目的使用多个不同的工作队列,该怎么办?最好只传递希望对象使用的队列,而不是让对象引用全局变量。在

.I opened a common DB connection and allowed every thread to use it.

数据库连接不是线程安全的,所以当您这样做时,可能会发生随机事件。 如文件所述:

The MySQL protocol can not handle multiple threads using the same connection at once. ... The general upshot of this is: Don't share connections between threads.

因此,您应该做的是,每个线程使用一个连接,正如您所发现的那样,它工作得很好。这与使用Queue的方式不同,在示例代码中,当您访问它时,它是正确锁定的。在

相关问题 更多 >

    热门问题