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/

 

作者:阿凡卢

出处:http://www.cnblogs.com/luxiaoxun/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

http://www.cnblogs.com/luxiaoxun/p/3827022.html

时间: 2024-08-11 04:55:14

python多线程编程的相关文章

Python多线程编程学习

Python 提供了几个用于多线程编程的模块,包括thread, threading 和Queue 等.thread 和threading 模块允许程序员创建和管理线程.thread 模块提供了基本的线程和锁的支持,而threading提供了更高级别,功能更强的线程管理的功能.Queue 模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构. 注意:避免使用thread模块,因为它不支持守护线程.当主线程退出时,所有的子线程不论它们是否还在工作,都会被强行退出. 下面重点说说threa

Python多线程编程(一):threading模块综述_python

Python这门解释性语言也有专门的线程模型,Python虚拟机使用GIL(Global Interpreter Lock,全局解释器锁)来互斥线程对共享资源的访问,但暂时无法利用多处理器的优势.在Python中我们主要是通过thread和 threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用 threading模块实现多线程编程.这篇文章我们主要来看看Python对多线程编程的支持. 在语言层面,Pyt

Python多线程编程(四):使用Lock互斥锁_python

前面已经演示了Python:使用threading模块实现多线程编程二两种方式起线程和Python:使用threading模块实现多线程编程三threading.Thread类的重要函数,这两篇文章的示例都是演示了互不相干的独立线程,现在我们考虑这样一个问题:假设各个线程需要访问同一公共资源,我们的代码该怎么写? 复制代码 代码如下: ''' Created on 2012-9-8   @author: walfred @module: thread.ThreadTest3 '''  impor

python多线程编程中的join函数使用心得_python

今天去辛集买箱包,下午挺晚才回来,又是恶心又是头痛.恶心是因为早上吃坏东西+晕车+回来时看到车祸现场,头痛大概是烈日和空调混合刺激而成.没有时间没有精神没有力气学习了,这篇博客就说说python中一个小小函数. 由于坑爹的学校坑爷的专业,多线程编程老师从来没教过,多线程的概念也是教的稀里糊涂,本人python也是菜鸟级别,所以遇到多线程的编程就傻眼了,别人用的顺手的join函数我却偏偏理解不来.早上在去辛集的路上想这个问题想到恶心,回来后继续写代码测试,终于有些理解了(python官方的英文解释

Python多线程编程(五):死锁的形成_python

前一篇文章Python:使用threading模块实现多线程编程四[使用Lock互斥锁]我们已经开始涉及到如何使用互斥锁来保护我们的公共资源了,现在考虑下面的情况– 如果有多个公共资源,在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,这会引起什么问题? 死锁概念 所谓死锁: 是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去.此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程.

Python多线程编程(八):使用Event实现线程间通信_python

使用threading.Event可以实现线程间相互通信,之前的Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]我们已经初步实现了线程间通信的基本功能,但是更为通用的一种做法是使用threading.Event对象.使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,Event默认内置了一个标志,初始值为False.一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set

Python多线程编程(二):启动线程的两种方法_python

在Python中我们主要是通过thread和threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用threading模块实现多线程编程.一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行:另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里. 将函数传递进Thread对象 复制代码 代码如下: '''  Cr

python多线程编程方式分析示例详解_python

在Python多线程中如何创建一个线程对象如果你要创建一个线程对象,很简单,只要你的类继承threading.Thread,然后在__init__里首先调用threading.Thread的__init__方法即可 复制代码 代码如下: import threading  class mythread(threading.Thread):  def __init__(self, threadname):  threading.Thread.__init__(self, name = thread

python多线程编程简单例子

我喜欢用代码来理解程序,而不是单单的教程 类 ThreadClass 继承自 threading.Thread,也正因为如此,您需要定义一个 run 方法,以此执行您在该线程中要运行的代码.在这个 run 方法中唯一要注意的是,self.getName()是一个用于确定该线程名称的方法.  代码如下 复制代码 #! /usr/bin/env python #coding=utf-8 import threading import datetime import time import rando