多线程

作者: 一月芷 | 来源:发表于2019-02-20 12:30 被阅读10次

    import threading
    import time

    def target():
        print 'the curent threading  %s is running' % threading.current_thread().name #获取线程名称
        time.sleep(1)
        print 'the curent threading  %s is ended' % threading.current_thread().name
     
    print 'the curent threading  %s is running' % threading.current_thread().name
    t = threading.Thread(target=target)
     
    t.start()
    t.join()
    print 'the curent threading  %s is ended' % threading.current_thread().name
     
    输出:
    the curent threading  MainThread is running
    the curent threading  Thread-1 is running
    the curent threading  Thread-1 is ended
    the curent threading  MainThread is ended
    

    start是启动线程join是阻塞当前线程即使得在当前线程结束时,不会退出。从结果可以看到,主线程直到Thread-1结束之后才结束。

    如果不加join语句,那么主线程不会等到当前线程结束才结束,但却不会立即杀死该线程。如不加join输出如下

    但如果为线程实例添加t.setDaemon(True)之后,如果不加join语句,那么当主线程结束之后,会杀死子线程如果加上join,并设置等待时间,就会等待线程一段时间再退出

    map实现多线程

    urls = ['http://www.baidu.com','http://www.sina.com','http://www.qq.com']
    results=map(urllib.requests.urlopen,urls)
    

    在 Python 中有个两个库包含了 map 函数: multiprocessing 和它鲜为人知的子库 multiprocessing.dummy.dummy 是 multiprocessing 模块的完整克隆,唯一的不同在于 multiprocessing 作用于进程,而 dummy 模块作用于线程。代码:

    import urllib
    import requests
    
    from multiprocessing.dummy import Pool as ThreadPool
     
    urls = ['http://www.baidu.com','http://www.sina.com','http://www.qq.com']
     
    pool = ThreadPool()
     
    results = pool.map(urllib.requests.urlopen,urls)
    print results
    pool.close()
    pool.join()
     
    print 'main ended'
    
    • pool = ThreadPool()创建了线程池,其默认值为当前机器 CPU 的核数,可以指定线程池大小,不是越多越好,因为越多的话,线程之间的切换也是很消耗资源的。
    • results = pool.map(urllib2.urlopen,urls) 该语句将不同的url传给各自的线程,并把执行后结果返回到results中。

    相关文章

      网友评论

          本文标题:多线程

          本文链接:https://www.haomeiwen.com/subject/mrzcyqtx.html