2012-02-07 36 views

回答

0

感谢您的一些信息,我只能猜测。

可能您从多个线程访问数据库时未锁定。那很糟。

在访问您的数据库时,您应该锁定threading.Lock()threading.RLock()。这可以防止几个线程干扰其他线程的操作。

+0

不过,如果我不共享的对象和单用,然后提示错误ProgrammingError来完成:(2014年,“命令不同步;你现在不能运行这个命令“ – 2012-02-07 11:05:36

12

根据PEP 249,数据访问模块具有模块级恒定threadsafety

Integer constant stating the level of thread safety the interface supports. Possible values are:

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.

根据MySQLdb User's Guide,该模块支持水平1.

The MySQL protocol can not handle multiple threads using the same connection at once. Some earlier versions of MySQLdb utilized locking to achieve a threadsafety of 2. While this is not terribly hard to accomplish using the standard Cursor class (which uses mysql_store_result()), it is complicated by SSCursor (which uses mysql_use_result(); with the latter you must ensure all the rows have been read before another query can be executed. It is further complicated by the addition of transactions, since transactions start when a cursor execute a query, but end when COMMIT or ROLLBACK is executed by the Connection object. Two threads simply cannot share a connection while a transaction is in progress, in addition to not being able to share it during query execution. This excessively complicated the code to the point where it just isn't worth it.

The general upshot of this is: Don't share connections between threads. It's really not worth your effort or mine, and in the end, will probably hurt performance, since the MySQL server runs a separate thread for each connection. You can certainly do things like cache connections in a pool, and give those connections to one thread at a time. If you let two threads use a connection simultaneously, the MySQL client library will probably upchuck and die. You have been warned.

+0

但是如果我没有共享对象并使用单例,那么它会给出错误ProgrammingError :(2014,”命令不同步;你现在不能运行这个命令“) – 2012-02-07 11:03:35

+2

@GaneshGhalame你需要多个连接对象,而不是单身。 – 2012-02-07 11:59:48

2

这里是有关该错误的细节:http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html

MySQLdb的手册建议这些:

不要线程之间共享连接。这真的不值得你的努力或我的努力,最终可能会损害性能,因为MySQL服务器为每个连接运行一个单独的线程。你当然可以做一些事情,比如缓存池中的连接,并且一次将这些连接提供给一个线程。如果你让两个线程同时使用一个连接,MySQL客户端库可能会挂起并死掉。你被警告了。

对于线程应用程序,请尝试使用连接池。这可以通过使用池模块

查看MySQLdb manual更多信息搜索关键字threadsafety,

+0

非常感谢它为我工作 – 2012-02-07 13:07:57