Python线程 - 访问postgreSQL时崩溃

时间:2009-07-18 21:50:51

标签: python postgresql

这是一个简单的线程程序,工作正常:

import psycopg2
import threading
import time

class testit(threading.Thread):
    def __init__(self, currency):
        threading.Thread.__init__(self)
        self.currency = currency

    def run(self):
        global SQLConnection
        global cursor
        SQLString = "Select dval from ddata where dname ='%s' and ddate = '2009-07-17'" \
                %self.currency
        z = time.time()
        while (time.time() - z) < 2:
            print SQLString

SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx")
cursor = SQLConnection.cursor()

a = testit('EURCZK')
b = testit('EURPLN')
a.start()
b.start()

然而,当我尝试使用以下代码开始访问线程中的postgresql数据库时,我总是遇到停止标志崩溃:

import psycopg2
import threading
import time

class testit(threading.Thread):
    def __init__(self, currency):
        threading.Thread.__init__(self)
        self.currency = currency

    def run(self):
        global SQLConnection
        global cursor
        SQLString = "Select dval from ddata where dname ='%s'and ddate = '2009-07-17'" %self.currency
        z = time.time()
        while (time.time() - z) < 2:
            cursor.execute(SQLString)
            print cursor.fetchall()

SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx")
cursor = SQLConnection.cursor()

a = testit('EURCZK')
b = testit('EURPLN')
a.start()
b.start()

两者之间的唯一区别在于while循环。我对线程编程很新。 postgres库(psycopg2)不是“线程安全”吗?所有这些都在Windows XP上运行。我能做什么?

感谢。

2 个答案:

答案 0 :(得分:2)

global SQLConnection
global cursor

似乎你是从多个线程访问全局变量?除非这些全局变量是线程安全的,否则你应该永远这样做,或者你自己提供适当的锁定。

您现在有2个线程访问相同的连接和相同的游标。他们会踩到每个人的脚趾。 psycopg2连接可能是线程安全的,但游标不是。

每个线程使用一个游标(可能还有一个连接)。

答案 1 :(得分:0)

宾果它正在工作。有人留下了答案,但似乎已将其删除,为每个线程提供自己的连接。是的,解决了它。所以这段代码有效:

import psycopg2
import threading
import time

class testit(threading.Thread):
    def __init__(self, currency):
        threading.Thread.__init__(self)
        self.currency = currency 
        self.SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx")
        self.cursor = self.SQLConnection.cursor()

    def run(self):
        SQLString = "Select dval from ddata where dname ='%s' and ddate = '2009-07-17'" \
                %self.currency
        z = time.time()
        while (time.time() - z) < 2:
            self.cursor.execute(SQLString)
            print self.cursor.fetchall()

a = testit('EURCZK')
b = testit('EURPLN')
a.start()
b.start()