我有一个函数readLatestOp(),该函数与mongodb和sqlite交互。我想同时运行此函数的多个实例来测试我的并发控制机制。我该如何解决这个问题。所以我想调用readLatestOp()10次,同时运行它们
def readLatestOp():
try:
account = raw_input("Enter the account ID: ")
started = time.clock()
calSTime = datetime.datetime.utcnow()
print(calSTime)
cursor = conn.execute("select * from SNAPSHOT_ISOLATION where DEST_ID = ? AND T_COMMIT ISNULL OR SOURCE_ID = ? and T_COMMIT ISNULL", (account, account))
result = (cursor.fetchone())
while time.clock() - started < 5 and result is not None:
cursor = conn.execute("select * from SNAPSHOT_ISOLATION where DEST_ID = ? AND T_COMMIT ISNULL OR SOURCE_ID = ? and T_COMMIT ISNULL", (account, account))
result = (cursor.fetchone())
findLatest = db.accounts.find_one({"_id" : account})
calFTime = datetime.datetime.utcnow()
print(calFTime)
except ValueError as err:
print(err)
print('You entered a wrong error')
sys.exit(1)
if result is not None:
print("Data not avaialable")
else:
return findLatest
答案 0 :(得分:0)
您可以使用multiprocessing
:
import multiprocessing
processes = []
for i in range(10):
process = multiprocessing.Process(target=readLatestOp)
processes.append(process)
process.start()
print('10 processes started.')
for process in processes:
process.join()
print('10 processes finished.')
import multiprocessing
import random
import time
def do_work(process_id):
time.sleep( random.randint(1,10) )
print '1 from process:', process_id
time.sleep( random.randint(1,10) )
print '2 from process:', process_id
processes = []
for i in range(3):
process = multiprocessing.Process(target=do_work, args=[i])
processes.append(process)
process.start()
print('3 processes started.')
for process in processes:
process.join()
print('3 processes finished.')
3 processes started.
1 from process: 2
2 from process: 2
1 from process: 1
2 from process: 1
1 from process: 0
2 from process: 0
3 processes finished.