2009-07-18 54 views
1

這裏是一個簡單的線程程序的正常工作: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上運行。我能做什麼?

謝謝。

+0

psycopg可以做到這一點。什麼是你正在得到確切的錯誤信息? – Christopher 2009-07-18 22:00:15

+0

沒有錯誤信息克里斯托弗 - 只有一個大窗口停止標記,它無法讀取一些內存位置。所以適當的系統級別崩潰。我將嘗試爲每個線程提供自己的連接和遊標。 – 2009-07-18 22:02:20

+0

呵呵。好的。那麼,http://www.free-soft.org/FSM/english/issue01/fog.html表明您的原始嘗試是有效的。也許這在v2中已經改變了。 – Christopher 2009-07-18 22:13:47

回答

2
global SQLConnection 
global cursor 

似乎你是從多個線程訪問全局變量?你應該從來沒有這樣做,除非這些全局變量是線程安全的,或者你自己提供適當的鎖定。

您現在有2個線程訪問相同的連接和相同的遊標。他們會踩着彼此的腳趾。 psycopg2連接可能是線程安全的,但遊標不是。

每個線程使用一個遊標(可能是一個連接)。

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()