How can I use threading in Python?

前端 未结 19 2679
迷失自我
迷失自我 2020-11-21 04:54

I am trying to understand threading in Python. I\'ve looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I\'m having trou

19条回答
  •  独厮守ぢ
    2020-11-21 05:19

    I found this very useful: create as many threads as cores and let them execute a (large) number of tasks (in this case, calling a shell program):

    import Queue
    import threading
    import multiprocessing
    import subprocess
    
    q = Queue.Queue()
    for i in range(30): # Put 30 tasks in the queue
        q.put(i)
    
    def worker():
        while True:
            item = q.get()
            # Execute a task: call a shell program and wait until it completes
            subprocess.call("echo " + str(item), shell=True)
            q.task_done()
    
    cpus = multiprocessing.cpu_count() # Detect number of cores
    print("Creating %d threads" % cpus)
    for i in range(cpus):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()
    
    q.join() # Block until all tasks are done
    

提交回复
热议问题