Python 学习——多线程

使用Threading模块创建线程:

threading模块有Thread类实现threading。Thread类提供的方法如下:

  run():线程的入口点
  start():调用run方法启动线程
  join(time):等待线程结束
  isAlive():检查一个线程是否仍旧在执行
  getName():返回线程的名字
  setName():设置一个线程的名字

要使用threading模块实现一个新线程,你得先如下做:
定义Thread类的一个子类。
  重写__init__(self,[,args])方法以增加额外的参数
  然后,重写run(self[,args])方法以实现线程启动后要做的事情
  在你创建新的Thread子类以后,你可以创建它的一个实例,然后引用start()来开启一个新线程,它会依次调用call方法。

1. 一般线程:

例子:

#!/usr/bin/python  

import threading
import time  

exitFlag = 0  

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name  

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            thread.exit()
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1  

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)  

# Start new Threads
thread1.start()
thread2.start()  

print "Exiting Main Thread"

2. 同步线程:
  Python提供的threading模块包括一个易于实现的锁定机制,以允许你同步线程。创建一个新锁通过调用Lock()实现,它也返回这个新锁。

新锁对象的accquire(blocking)方法,用来强制线程同步运行。可选的blocking参数使你能够控制线程是否请求锁。

  如果blocking设置为0,线程在不能获取锁时立即返回0值;而blocking设置为1时,线程获取锁以后返回1值。如果blocking设置为1,线程将会阻塞,一直等到锁释放。

  新锁对象的release()方法用来释放不再需要的锁。

例子:

#!/usr/bin/python  

import threading
import time  

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        # Get lock to synchronize threads
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Free lock to release next thread
        threadLock.release()  

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1  

threadLock = threading.Lock()
threads = []  

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)  

# Start new Threads
thread1.start()
thread2.start()  

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)  

# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"

3. 多线程优先级队列:

Queue模块允许你创建一个新的队列对象,以盛放一定数量的项目。

控制Queue有以下方法:

  get():从队列移除一个项目并返回它

  put():把项目放入队列

  qsize():返回当前队列中项目的数量

  empty():如果队列为空,返回True,反之为False

  full():如果队列满了返回True,反之为False

例子:

#!/usr/bin/python  

import Queue
import threading
import time  

exitFlag = 0  

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print "Starting " + self.name
        process_data(self.name, self.q)
        print "Exiting " + self.name  

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print "%s processing %s" % (threadName, data)
        else:
            queueLock.release()
        time.sleep(1)  

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1  

# Create new threads
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1  

# Fill the queue
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()  

# Wait for queue to empty
while not workQueue.empty():
    pass  

# Notify threads it‘s time to exit
exitFlag = 1  

# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"  
时间: 2024-08-07 14:50:50

Python 学习——多线程的相关文章

python学习 —— 多线程发送请求测试服务器压力

以前写过的python多线程终于派上用场了,其实还没开始测试,但下周会使用这个脚本测试一下,虽然boss让我用C++来做: # coding=utf-8 import random import string import threading import time from requests import post class MultiThread(threading.Thread): def __init__(self, url, qlock): threading.Thread.__in

python学习——多线程

多任务可以由多进程完成,也可以由一个进程内的多线程完成. 我们前面提到了进程是由若干线程组成的,一个进程至少有一个线程. 由于线程是操作系统直接支持的执行单元,因此,高级语言通常都内置多线程的支持,Python也不例外,并且,Python的线程是真正的Posix Thread,而不是模拟出来的线程. Python的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装.绝大多数情况下,我们只需要使用thread

python 学习_第四模块 并发编程(多线程)

python 学习_第四模块 并发编程(多线程) 1  开启线程方式 from threading import Thread import time def say(name): time.sleep(2) print("%s hello"%name) if __name__ =="__main__": t = Thread(target=say,args=("alex",)) t.start() print("主线程")

OpenCV之Python学习笔记

OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书<OpenCV Computer Vision with Python>,于是就看一遍,顺便把自己掌握的东西整合一下,写成学习笔记了.更需要的朋友参考. 阅读须知: 本文不是纯粹的译文,只是比较贴近原文的笔记:         请设法购买到出版社出版的书,支持正版. 从书名就能看出来本书是介绍在Pytho

python 学习总结2 多进程

多进程: 我们什么时候需要多进程呢?我们知道python的多线程,实际不是真实的多线程,它同一时间在一个cpu执行一个任务,它通过上下文的切换来让我看起来是多并发的, 那么如果我们想要真正实现多个任务在多个cpu上同时执行,我们就需要多进程的性质来帮忙了(python的多线程不适合cpu密集型的任务,适合io密集型的任务). import multiprocessing import threading def thread_run(): print(threading.get_ident())

Python 学习参考书目推荐

Python 学习,参考书目推荐 前言 好的技术书籍可以帮助我们快速地成长,大部分人或多或少地受益于经典的技术书籍.在「Python开发者」微信公号后台,我们经常能收到让帮忙推荐书籍的消息.这类的问题在@Python开发者 微博 和 伯乐在线的 Python小组 讨论中也不绝于耳. 7月3日,伯乐在线在「Python开发者」微信公号发起了一个讨论 (注:PC端无法看到大家的评论,需要关注微信公号后,从微信才可以看到),通过这个讨论话题,在评论中分享对自己帮助很大的Python技术书籍.  (Py

Python学习的个人笔记(基础语法)

Python学习的个人笔记 题外话: 我是一个大二的计算机系的学生,这份python学习个人笔记是趁寒假这一周在慕课网,w3cschool,还有借鉴了一些博客,资料整理出来的,用于自己方便的时候查阅,一开始保存在word上,代码不是很好看,于是决定复制到博客里面,可能有复制过程中出错的,或者我本身在理解方面有出错的地方,希望能得到指正,谢谢  后续的内容我会继续学习…… python下载地址  www.python.org Python 分为2.7和3.3两个版本,3.3有些库不兼容,因此用2.

【学院官方整理】Python学习路线图-适合自学者从入门到项目开发(视频+文档) 干货提炼

亲爱的学员们: 您好!51CTO学院为梦想增值,诚邀您的关注!51CTO学院致力于让专家分享技术并让技术变现,让广大技术爱好者便捷.实惠的获取优质学习资源. 为了方便大家的学习,我们特别整理了Python学习路线图-适合自学者从入门到项目开发(视频+文档) 干货提炼,点击查看更多>> Python学习路线图-适合自学者从入门到项目开发(视频+文档) 干货提炼 本专题涵盖了Python基础.网络编程.WEB开发基础.WEB框架.分布式监控开发.审计堡垒机.FTP服务器.CMDB.主机批量管理.W

Python学习 Week1

什么是Python? 是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年.(摘自百度百科) Python的优缺点 先看优点 Python的定位是"优雅"."明确"."简单",所以Python程序看上去总是简单易懂,初学者学Python,不但入门容易,而且将来深入下去,可以编写那些非常非常复杂的程序. 开发效率非常高,Python有非常强大的第三方库,基本上你想通过计