Skip to content

Commit c83542e

Browse files
committed
the Redis class is now a thread local. This means you can safely pass it around between threads and connections will get swapped out correctly.
1 parent 800720c commit c83542e

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

redis/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def zset_score_pairs(response, **options):
143143
return zip(response[::2], map(float, response[1::2]))
144144

145145

146-
class Redis(object):
146+
class Redis(threading.local):
147147
"""
148148
Implementation of the Redis protocol.
149149

tests/connection_pool.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import redis
2+
import threading
3+
import time
24
import unittest
35

46
class ConnectionPoolTestCase(unittest.TestCase):
@@ -17,4 +19,27 @@ def test_multiple_connections(self):
1719
r2.select('localhost', 6379, db=9)
1820
self.assertEquals(r1.connection, r2.connection)
1921

20-
22+
def test_threaded_workers(self):
23+
r = redis.Redis(host='localhost', port=6379, db=9)
24+
r.set('a', 'foo')
25+
r.set('b', 'bar')
26+
27+
def _info_worker():
28+
for i in range(50):
29+
_ = r.info()
30+
time.sleep(0.01)
31+
32+
def _keys_worker():
33+
for i in range(50):
34+
_ = r.keys()
35+
time.sleep(0.01)
36+
37+
t1 = threading.Thread(target=_info_worker)
38+
t2 = threading.Thread(target=_keys_worker)
39+
t1.start()
40+
t2.start()
41+
42+
for i in [t1, t2]:
43+
i.join()
44+
45+

0 commit comments

Comments
 (0)