Wednesday, September 26, 2007

Contoh Multi Threading di Python

Studi kasus : mengupdated 1 row database secara bersamaan untuk melihat apakah Transaction di MySQL berfungsi dengan baik.


import MySQLdb
import threading


class MultiThread(threading.Thread):
def __init__(self, cx):
super(MultiThread,self).__init__()
self.counter = cx

def run(self):
myconn = MySQLdb.Connect(host='localhost',user='root',passwd='a',db='DTSClient')
myconn.autocommit(1)
mysql = "Call testproc(1,1);"
mycursor = myconn.cursor()
result = mycursor.execute(mysql)
print result
myconn.close()

blist = []
for cx in range(50):
bg = MultiThread(cx)
blist.append(bg)

for bx in blist:
bx.start()


Untuk stored procedure dengan menggunakan Transaction lihat blog sebelum ini.

Stored Procedure di MySQL

Contoh stored procedure di MySQL:


DROP PROCEDURE testproc;
DELIMITER //
CREATE PROCEDURE testproc (IN pid INT, IN pamount INT)
BEGIN

DECLARE bal INT;

START TRANSACTION;
SELECT balance INTO bal FROM test1 where id = pid;
UPDATE test1 SET balance = (bal + pamount) WHERE id = pid;
COMMIT;

END;
//
DELIMITER ;


Statement DELIMITER sangat penting, kalau tidak MySQL akan memberikan pesan ERROR.