美文网首页
Python多线程,多进程

Python多线程,多进程

作者: Eoccc | 来源:发表于2019-02-25 17:06 被阅读0次

    以实用为目的,记几个python的多线程,多进程模块

    # 先定义需要执行的任务函数
    def do_job(arg):
        print 'hello', arg
        return arg + ', done'
    

    一、多线程

    Thread模块

    import Thread
    
    # 使用start_new_thread开启新线程
    thread.start_new_thread(printArg, 'Anne')
    

    Threading模块

    import threading
    
    threads = []
    for arg in arg_list:
        t = threading.Thread(target=printArg, name=None, args=(arg)) 
        t.start()
        threads.append(t)
    
    [t.join() for t in threads]
    

    当多线程需要共享数据时,使用线程锁实现简单的线程同步。Threading提供两个线程锁:Lock(),Rlock(),Lock属于全局,Rlock属于线程,推荐使用Rlock()。

    def do_job(arg):
        lock = threading.RLock()
        lock.acquire()
        print arg  # do something
        lock.release()
    

    注意:线程锁应该使用在线程内部

    二、 线程池

    threadpool模块

    import threadpool
    

    创建线程池,并定义参数

    poolsize = 5
    list_of_args = [1,2,3,4,5]
    pool = ThreadPool(poolsize)
    

    创建线程请求,可以定义callback函数

    requests = threadpool.makeRequests(some_callable, list_of_arg, callback=None)  
    

    执行每个线程

    result = [pool.putRequest(req) for req in requests]
    pool.wait()  # 等待所有的线程完成
    

    相关文章

      网友评论

          本文标题:Python多线程,多进程

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