Skip to content

Commit c1dfe56

Browse files
Add sample demonstrating the use of threads and concurrent execution of
database operations.
1 parent 8a7c310 commit c1dfe56

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

python/Threads.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# Threads.py
7+
# This script demonstrates the use of threads with cx_Oracle. A session pool
8+
# is used so that multiple connections are available to perform work on the
9+
# database. Only one operation (such as an execute or fetch) can take place at
10+
# a time on a connection. In the below example, one of the threads performs
11+
# dbms_lock.sleep while the other performs a query.
12+
#
13+
# This script requires cx_Oracle 2.5 and higher.
14+
#------------------------------------------------------------------------------
15+
16+
from __future__ import print_function
17+
18+
import cx_Oracle
19+
import threading
20+
21+
pool = cx_Oracle.SessionPool("cx_Oracle", "dev", "localhost/orcl", 2, 5, 1,
22+
threaded = True)
23+
24+
def TheLongQuery():
25+
conn = pool.acquire()
26+
cursor = conn.cursor()
27+
cursor.arraysize = 25000
28+
print("TheLongQuery(): beginning execute...")
29+
cursor.execute("""
30+
select *
31+
from
32+
TestNumbers
33+
cross join TestNumbers
34+
cross join TestNumbers
35+
cross join TestNumbers
36+
cross join TestNumbers
37+
cross join TestNumbers""")
38+
print("TheLongQuery(): done execute...")
39+
while True:
40+
rows = cursor.fetchmany()
41+
if not rows:
42+
break
43+
print("TheLongQuery(): fetched", len(rows), "rows...")
44+
print("TheLongQuery(): all done!")
45+
46+
47+
def DoALock():
48+
conn = pool.acquire()
49+
cursor = conn.cursor()
50+
print("DoALock(): beginning execute...")
51+
cursor.callproc("dbms_lock.sleep", (5,))
52+
print("DoALock(): done execute...")
53+
54+
55+
thread1 = threading.Thread(None, TheLongQuery)
56+
thread1.start()
57+
58+
thread2 = threading.Thread(None, DoALock)
59+
thread2.start()
60+
61+
thread1.join()
62+
thread2.join()
63+
64+
print("All done!")
65+

0 commit comments

Comments
 (0)