|
| 1 | +# Copyright 2023 by Teradata Corporation. All rights reserved. |
| 2 | + |
| 3 | +# This sample program demonstrates how to use multiple threads to load data in parallel. |
| 4 | + |
| 5 | +import teradatasql |
| 6 | +import threading |
| 7 | +import time |
| 8 | + |
| 9 | +def WorkerThread (con, sTableName, aaoData): |
| 10 | + |
| 11 | + t = threading.current_thread () |
| 12 | + |
| 13 | + # Connection objects are thread safe. Threads can share a connection. |
| 14 | + # Cursor objects are not thread safe. Each thread needs its own cursor. |
| 15 | + |
| 16 | + with con.cursor () as cur: |
| 17 | + |
| 18 | + sql = "create volatile table " + sTableName + " (c1 integer, c2 varchar(100)) on commit preserve rows" |
| 19 | + print ("Worker thread", t.ident, sql) |
| 20 | + cur.execute (sql) |
| 21 | + |
| 22 | + sql = "insert into " + sTableName + " values (?, ?)" |
| 23 | + print ("Worker thread", t.ident, sql) |
| 24 | + cur.execute (sql, aaoData) |
| 25 | + |
| 26 | + # end WorkerThread |
| 27 | + |
| 28 | +with teradatasql.connect (host="whomooz", user="guest", password="please") as con: |
| 29 | + |
| 30 | + tMain = threading.current_thread () |
| 31 | + |
| 32 | + tWorker1 = threading.Thread (target=WorkerThread, args=(con, "voltab1", [ |
| 33 | + [1, "abc"], |
| 34 | + [2, "def"], |
| 35 | + [3, "ghi"], |
| 36 | + ])) |
| 37 | + print ("Main thread", tMain.ident, "starting worker thread #1") |
| 38 | + tWorker1.start () |
| 39 | + |
| 40 | + tWorker2 = threading.Thread (target=WorkerThread, args=(con, "voltab2", [ |
| 41 | + [10, "rst"], |
| 42 | + [20, "uvw"], |
| 43 | + [30, "xyz"], |
| 44 | + ])) |
| 45 | + print ("Main thread", tMain.ident, "starting worker thread #2") |
| 46 | + tWorker2.start () |
| 47 | + |
| 48 | + print ("Main thread", tMain.ident, "waiting for worker thread", tWorker1.ident, "to finish") |
| 49 | + tWorker1.join () |
| 50 | + print ("Main thread", tMain.ident, "done waiting for worker thread", tWorker1.ident) |
| 51 | + |
| 52 | + print ("Main thread", tMain.ident, "waiting for worker thread", tWorker2.ident, "to finish") |
| 53 | + tWorker2.join () |
| 54 | + print ("Main thread", tMain.ident, "done waiting for worker thread", tWorker2.ident) |
| 55 | + |
| 56 | + with con.cursor () as cur: |
| 57 | + |
| 58 | + sql = "select * from voltab1 order by 1 ; select * from voltab2 order by 1" |
| 59 | + print ("Main thread", tMain.ident, sql) |
| 60 | + cur.execute (sql) |
| 61 | + [ print (row) for row in cur.fetchall () ] |
| 62 | + cur.nextset () |
| 63 | + [ print (row) for row in cur.fetchall () ] |
0 commit comments