美文网首页
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多线程,多进程

    以实用为目的,记几个python的多线程,多进程模块 一、多线程 Thread模块 Threading模块 当多线...

  • Python time、进程、线程、协程(异步IO)

    Python既支持多进程,又支持多线程 time 多进程 multiprocessing 通常在计算密集型时使用多...

  • 多进程和多线程编程

    多任务的实现方式: 多进程模式 多线程模式 多进程 + 多线程 模式python即支持多进程,又支持多线程,如下进...

  • python 进程,队列

    1.进程,队列 在python中虽然不能发挥多线程的优势,但是对于tensorflow中,多线程任务,我们可以写多...

  • 浅析python的GIL

    Python中的GIL锁 在Python中,可以通过多进程、多线程和多协程来实现多任务。 在多线程的实现过程中,为...

  • [CP_12] Python多线程爬虫应用实践(社招职位名称获取

    目录结构 一、多线程爬虫的使用 1. 多线程实现 <关联> [Pt_04] Python进程|多进程|线程|多线程...

  • GIL

    谈谈python的GIL、多线程、多进程 最近在看 Python 的多线程,经常我们会听到老手说:“python下...

  • python爬虫--day06

    进程 进程的概念 python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python...

  • 浅谈python中的多线程和多进程(二)

    原创:hxj7 本文继续分享一个关于python多线程和多进程区别的例子 前文《浅谈python中的多线程和多进程...

  • Python3 异步协程函数async具体用法

    之前使用Python的人往往纠缠在多线程,多进程,评判哪个效率更高?其实,相对于别家的协程和异步,不管多线程还是多...

网友评论

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

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