Execute multiple threads concurrently

后端 未结 3 1779
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 15:50

Current code is:

def export_data(file):
    

def export_to_files(yaml):
    logger = logging.g         


        
相关标签:
3条回答
  • 2020-11-30 15:57

    Your visible code is fine, however some code invisible to us does use locking, the locking can happen even in the database itself.

    0 讨论(0)
  • 2020-11-30 15:58

    This illustrates a runnable version of your example code:

    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()
    
    0 讨论(0)
  • 2020-11-30 16:04

    You could use the largely undocumented ThreadPool class in multiprocessing.pool to do something along these lines:

    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()
    

    Example output:

    [ 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...
    
    0 讨论(0)
提交回复
热议问题