How can I use threading in Python?

前端 未结 19 2755
迷失自我
迷失自我 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条回答
  •  Happy的楠姐
    2020-11-21 05:30

    The answer from Alex Martelli helped me. However, here is a modified version that I thought was more useful (at least to me).

    Updated: works in both Python 2 and Python 3

    try:
        # For Python 3
        import queue
        from urllib.request import urlopen
    except:
        # For Python 2 
        import Queue as queue
        from urllib2 import urlopen
    
    import threading
    
    worker_data = ['http://google.com', 'http://yahoo.com', 'http://bing.com']
    
    # Load up a queue with your data. This will handle locking
    q = queue.Queue()
    for url in worker_data:
        q.put(url)
    
    # Define a worker function
    def worker(url_queue):
        queue_full = True
        while queue_full:
            try:
                # Get your data off the queue, and do some work
                url = url_queue.get(False)
                data = urlopen(url).read()
                print(len(data))
    
            except queue.Empty:
                queue_full = False
    
    # Create as many threads as you want
    thread_count = 5
    for i in range(thread_count):
        t = threading.Thread(target=worker, args = (q,))
        t.start()
    

提交回复
热议问题