目前的代码是:
def export_data(file):
<runs the db2 database command to export tables to file>
def export_to_files(yaml):
logger = logging.getLogger("export_to_files")
thread1 = threading.Thread(target=export_data, args=[out_file1])
thread1.start()
thread2 = threading.Thread(target=export_data, args=[out_file2])
thread2.start()
thread1.join()
thread2.join()
def main():
export_to_files()
if __name__ == "__main__":
main()
我的理解是join()
只阻止调用线程。但是,我没有意识到thread1.join()
甚至会阻止thread2
执行,实质上使代码只运行1个线程,即thread1
。
如何同时执行两个线程,同时主线程等待两者完成?
编辑:我纠正了,2个线程确实运行了,但似乎只有1个线程在某个时间点实际上“做”了事情。进一步说明,callable_method
正在从数据库中读取数据并写入文件。虽然我现在可以看到2个文件正在更新(每个线程写入一个单独的文件),但其中一个文件现在已经很长时间没有更新,而另一个文件是最新的当前时间。
正在使用否连接对象。查询从db2命令行界面运行。
答案 0 :(得分:3)
您可以使用multiprocessing.pool
中基本未记录的ThreadPool
类来执行以下操作:
from multiprocessing.pool import ThreadPool
import random
import threading
import time
MAX_THREADS = 2
print_lock = threading.Lock()
def export_data(fileName):
# simulate writing to file
runtime = random.randint(1, 10)
while runtime:
with print_lock: # prevent overlapped printing
print('[{:2d}] Writing to {}...'.format(runtime, fileName))
time.sleep(1)
runtime -= 1
def export_to_files(filenames):
pool = ThreadPool(processes=MAX_THREADS)
pool.map_async(export_data, filenames)
pool.close()
pool.join() # block until all threads exit
def main():
export_to_files(['out_file1', 'out_file2', 'out_file3'])
if __name__ == "__main__":
main()
示例输出:
[ 9] Writing to out_file1...
[ 6] Writing to out_file2...
[ 5] Writing to out_file2...
[ 8] Writing to out_file1...
[ 4] Writing to out_file2...
[ 7] Writing to out_file1...
[ 3] Writing to out_file2...
[ 6] Writing to out_file1...
[ 2] Writing to out_file2...
[ 5] Writing to out_file1...
[ 1] Writing to out_file2...
[ 4] Writing to out_file1...
[ 8] Writing to out_file3...
[ 3] Writing to out_file1...
[ 7] Writing to out_file3...
[ 2] Writing to out_file1...
[ 6] Writing to out_file3...
[ 1] Writing to out_file1...
[ 5] Writing to out_file3...
[ 4] Writing to out_file3...
[ 3] Writing to out_file3...
[ 2] Writing to out_file3...
[ 1] Writing to out_file3...
答案 1 :(得分:0)
这说明了示例代码的可运行版本:
import time
import threading
def export_data(fileName):
# runs the db2 database command to export tables to file
while True:
print 'If I were the real function, I would be writing to ' + fileName
time.sleep(1)
thread1 = threading.Thread(target=export_data, args=[ 'out_file1' ])
thread2 = threading.Thread(target=export_data, args=[ 'out_file2' ])
thread1.start()
thread2.start()
thread1.join()
thread2.join()
答案 2 :(得分:0)
您的可见代码很好,但是我们看不到某些代码使用锁定,即使在数据库本身也可能发生锁定。