Is it allowed to reuse a connection on which another thread waits for notifications?

From: Jan Wrobel <wrr(at)mixedbit(dot)org>
To: psycopg(at)postgresql(dot)org
Subject: Is it allowed to reuse a connection on which another thread waits for notifications?
Date: 2013-03-13 11:32:33
Message-ID: CACm05o-q+uZvgeoeLu5ZBc5_j3T2JUBLOw2a--bS_gnMu3-acA@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: psycopg

Hello,

Recently I started to use LISTEN and NOTIFY with psycopg2 and I'm
experiencing rare hangs of the application. I suspect my notification
handling logic may be incorrect, in particular, I started to wonder
whether it is OK to share a connection between a thread that listens
for a notification and a thread that sends a notification.

My notification thread executes:

cursor = connection.cursor() # this connection has ISOLATION_LEVEL_AUTOCOMMIT
cursor.execute("NOTIFY " + channel + ", %s", [message])
cursor.close()

My listening thread executes:

cursor = connection.cursor() # This is the same connection that is
used by the NOTIFY thread.
cursor.execute('LISTEN %s;' % (channel))
while True:
if select.select([connection],[],[]) == ([],[],[]):
continue
connection.poll()
while connection.notifies:
notify = connection.notifies.pop()
self.handle_notify(notify.channel, notify.payload)

Is this approach correct, or should I use separate connection to send
notifications? I know that in general connections are thread safe, but
it is still true if one of the threads calls selects() with the
connection or can this cause a deadlock?

Best regards,
Jan

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2013-03-13 11:56:53 Re: Is it allowed to reuse a connection on which another thread waits for notifications?
Previous Message Don Parris 2013-03-13 09:21:10 Fwd: parameterized full text search problem