python多线程的几种方法

python多线程编程

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()

Python线程同步:

(1)Thread的Lock和RLock实现简单的线程同步:

import threading
import time
class mythread(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global x
        lock.acquire()
        for i in range(3):
            x = x+1
        time.sleep(1)
        print x
        lock.release()

if __name__ == ‘__main__‘:
    lock = threading.RLock()
    t1 = []
    for i in range(10):
        t = mythread(str(i))
        t1.append(t)
    x = 0
    for i in t1:
        i.start()

(2)使用条件变量保持线程同步:

# coding=utf-8
import threading

class Producer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global x
        con.acquire()
        if x == 10000:
            con.wait()
            pass
        else:
            for i in range(10000):
                x = x+1
                con.notify()
        print x
        con.release()

class Consumer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global x
        con.acquire()
        if x == 0:
            con.wait()
            pass
        else:
            for i in range(10000):
                x = x-1
            con.notify()
        print x
        con.release()

if __name__ == ‘__main__‘:
    con = threading.Condition()
    x = 0
    p = Producer(‘Producer‘)
    c = Consumer(‘Consumer‘)
    p.start()
    c.start()
    p.join()
    c.join()
    print x

(3)使用队列保持线程同步:

# coding=utf-8
import threading
import Queue
import time
import random

class Producer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global     queue
        i = random.randint(1,5)
        queue.put(i)
        print self.getName(),‘ put %d to queue‘ %(i)
        time.sleep(1)

class Consumer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global     queue
        item = queue.get()
        print self.getName(),‘ get %d from queue‘ %(item)
        time.sleep(1)

if __name__ == ‘__main__‘:
    queue = Queue.Queue()
    plist = []
    clist = []
    for i in range(3):
        p = Producer(‘Producer‘+str(i))
        plist.append(p)
    for j in range(3):
        c = Consumer(‘Consumer‘+str(j))
        clist.append(c)
    for pt in plist:
        pt.start()
        pt.join()
    for ct in clist:
        ct.start()
        ct.join()

生产者消费者模式的另一种实现:

# coding=utf-8
import time
import threading
import Queue

class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue

    def run(self):
        while True:
            # queue.get() blocks the current thread until an item is retrieved.
            msg = self._queue.get()
            # Checks if the current message is the "quit"
            if isinstance(msg, str) and msg == ‘quit‘:
                # if so, exists the loop
                break
            # "Processes" (or in our case, prints) the queue item
            print "I‘m a thread, and I received %s!!" % msg
        # Always be friendly!
        print ‘Bye byes!‘

class Producer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue

    def run(self):
        # variable to keep track of when we started
        start_time = time.time()
        # While under 5 seconds..
        while time.time() - start_time < 5:
            # "Produce" a piece of work and stick it in the queue for the Consumer to process
            self._queue.put(‘something at %s‘ % time.time())
            # Sleep a bit just to avoid an absurd number of messages
            time.sleep(1)
        # This the "quit" message of killing a thread.
        self._queue.put(‘quit‘)

if __name__ == ‘__main__‘:
    queue = Queue.Queue()
    consumer = Consumer(queue)
    consumer.start()
    producer1 = Producer(queue)
    producer1.start()

使用线程池(Thread pool)+同步队列(Queue)的实现方式:

# A more realistic thread pool example
# coding=utf-8
import time
import threading
import Queue
import urllib2 

class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue 

    def run(self):
        while True:
            content = self._queue.get()
            if isinstance(content, str) and content == ‘quit‘:
                break
            response = urllib2.urlopen(content)
        print ‘Bye byes!‘

def Producer():
    urls = [
        ‘http://www.python.org‘, ‘http://www.yahoo.com‘
        ‘http://www.scala.org‘, ‘http://cn.bing.com‘
        # etc..
    ]
    queue = Queue.Queue()
    worker_threads = build_worker_pool(queue, 4)
    start_time = time.time()
    # Add the urls to process
    for url in urls:
        queue.put(url)
    # Add the ‘quit‘ message
    for worker in worker_threads:
        queue.put(‘quit‘)
    for worker in worker_threads:
        worker.join()

    print ‘Done! Time taken: {}‘.format(time.time() - start_time)

def build_worker_pool(queue, size):
    workers = []
    for _ in range(size):
        worker = Consumer(queue)
        worker.start()
        workers.append(worker)
    return workers

if __name__ == ‘__main__‘:
    Producer()

另一个使用线程池+Map的实现:

import urllib2
from multiprocessing.dummy import Pool as ThreadPool 

urls = [
    ‘http://www.python.org‘,
    ‘http://www.python.org/about/‘,
    ‘http://www.python.org/doc/‘,
    ‘http://www.python.org/download/‘,
    ‘http://www.python.org/community/‘
    ]

# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join()

参考: http://blog.jobbole.com/58700

时间: 2024-07-30 10:29:16

python多线程的几种方法的相关文章

python多线程有几种实现方法

python多线程有几种实现方法,都是什么? 目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用.2.7版本之前python对线程的支持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading  模块.threading模块里面主要是对一些线程的操作对象化,创建Thread的c

实现多线程的两种方法:继承Thread类或实现Runnable接口

实现多线程的两种方法:继承Thread类或实现Runnable接口 Java中实现多线程有两种方法:继承Thread类和实现Runnable接口,在程序开发中只要是多线程,我们一般都是实现Runnable接口,原因归结为一点:实现接口比继承类要好. 多线程的第一种实现方式:继承Thread类 步骤如下 创建一个继承Thread的类(假定为A),并重写Thread的run方法 构造一个A类对象,假定为aa 调用aa的start方法.(start方法是从Thread继承过来的) 具体例子如下 pac

Python文件遍历二种方法

分享下有关Python文件遍历的两种方法,使用的OS模块的os.walk和os.listdir实现. 关于Python的文件遍历,大概有两种方法,一种是较为便利的os.walk(),还有一种是利用os.listdir()递归遍历.方法一:利用os.walkos.walk可以自顶向下或者自底向上遍历整个文件树,然后返回一个含有3个元素的tuple,(dirpath, dirnames, filenames).注意,os.walk()会返回一个generater,所以调用的时候一定要放到for循环中

Python并发编程之创建多线程的几种方法(二)

大家好,并发编程 进入第二篇. 今天的内容会比较基础,主要是为了让新手也能无障碍地阅读,所以还是要再巩固下基础.学完了基础,你们也就能很顺畅地跟着我的思路理解以后的文章. 本文目录 学会使用函数创建多线程 学会使用类创建多线程 多线程:必学函数讲解 经过总结,Python创建多线程主要有如下两种方法: 函数 类 接下来,我们就来揭开多线程的神秘面纱. . 学会使用函数创建多线程 在Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多线程.

python爬虫:两种方法模拟登录博客园

第一方法用第三方库(requests):参考http://www.mamicode.com/info-detail-1839685.html 源代码分析 博客园的登录页面非常简单,查看网页源代码,可以发现两个输入框的id分别为input1.input2,复选框的id为remember_me,登录按钮的id为signin. 还有一段JavaScript代码,下面来简单分析一下. 先来看$(function(){});函数: 1 $(function () { 2 $('#signin').bind

关于创建及使用多线程的几种方法

近期刚刚学习了一种多线程技术,现结合自己的理解将其罗列出来,希望能够与大家交流一下,多线程是一种能够节省程序运算时间的方法,大大的提高了程序的运算效率,那么首先我们来说一下进程和线程概念: 一个程序包含一个以上的进程,而一个进程又可以包含一个以上的线程,每一个进程都有自己独立的内存空间,相应的一个进程中的所有线程都共享该内存空间. 进程:是一个具有一定独立功能的程序关于某个数据集合的一次运行活动.它是操作系统动态执行的基本单元,在传统的操作系统中,进程既是基本的资源分配单元,也是基本的执行单元.

python调试的几种方法

调试 From :https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00138683229901532c40b749184441dbd428d2e0f8aa50e000 程序能一次写完并正常运行的概率很小,基本不超过1%.总会有各种各样的bug需要修正.有的bug很简单,看看错误信息就知道,有的bug很复杂,我们需要知道出错时,哪些变量的值是正确的,哪些变量的值是错误的,因此,需

python 类的几种方法(函数)

python中可以定义类,为面向对象语言. 在定义个class时,可以定义3中类型的方法.包括‘实例方法’.“类方法”,“静态方法”其中不同之处: python类的方法 类型 类访问 实例访问 意义 实例方法 不可以 可以   类方法 可以 可以   静态方法 可以 可以   1,实例方法 实例方法是最简单的一种方法,定义一个实例方法第一个默认的隐式传参标示调用当前方法的实例: #encoding:utf-8 #小五 class Person(object): def __init__(self

关于GCD学习,创建及使用多线程的几种方法

近期刚刚学习了一种多线程技术,现结合自己的理解将其罗列出来,希望能够与大家交流一下,多线程是一种能够节省程序运算时间的方法,大大的提高了程序的运算效率,那么首先我们来说一下进程和线程概念: 一个程序包含一个以上的进程,而一个进程又可以包含一个以上的线程,每一个进程都有自己独立的内存空间,相应的一个进程中的所有线程都共享该内存空间. 进程:是一个具有一定独立功能的程序关于某个数据集合的一次运行活动.它是操作系统动态执行的基本单元,在传统的操作系统中,进程既是基本的资源分配单元,也是基本的执行单元.