近期想学习研究一下python中使用多线程,来提高python在爬虫项目中的效率。

如今我们在网页上查询到在python中使用的多线程的使用大多数都是使用的threading模块,可是python中另一个模块叫做的thread模块,也能够完毕多线程的任务。

相比較两者来说。threading是更高级别的应用模块,但thread的存在必定有存在的理由。本篇主要讲介绍一下thread在python中的应用。

资源来自python开发文档的总结:

highlight=thread#module-thread">https://docs.python.org/2/library/thread.html?

highlight=thread#module-thread

thread模块提供了较底层的多线程处理模块(也被称作是轻量级的处理程序)。提供了同步和简单锁(mutexes或binary semaphores)的功能。

在IDLE中import thread之后,通过help(thread) 能够查看thread的相关类函数及接口函数,在帮助文档中我们主要看到了一些有关thread的lock。error相关的函数说明,线程相关的函数说明。

主要函数说明: thread对象有下面几个函数

thread.interrupt_main():在主线程中引发一个KeyboardInterrupt(一般是Ctrl+C或者是delete)异常。子线程能够通过这个函数中断主线程。

thread.exit():

触发SystemExit异常。假设没有被捕获(不作出处理)。将会影响此线程退出终止。

thread.allocate_lock():

返回一个新的lock对象,锁的方法下文将要介绍,这样的锁起初是没有锁定的。

thread.get_ident():

返回当前线程的id号,返回值为一个非零的整形,它的值没有直接的意义。

thread.stack_size([size])

当建立新的线程的时候 返回栈的大小。

Lock对象有下面一个函数说明:

lock.acquire([waitflag])

当这个函数没有括号里的可选參数的时候,这种方法能够无条件地捕获这个lock。假设此锁被占用 则该方法会等待该锁被释放后将其捕获。假设这个int型的可选參数存在的话,函数的行为和这个int的值有关系:

假设是0的话,在此lock能够被无条件地捕获的前提下 lock仅仅是被直接捕获;当waitflag为非0值时候。lock会像之前一样被无条件捕获。假设lock被成功捕获,则返回值为True,否则返回为False.

lock.release()

释放当前的lock对象;这里的lock必须是之前被捕获的,只是不要求是被同一个lock所捕获。

lock.locked():

返回当前所的状态。假设当前所被某个锁捕获,则返回值为True,否则返回为False.

另外,对于这些方法。lock对象也能够通过with声明来使用:

import thread  #导入thread模块
a_lock = thread.allocate_lock()
with a_lock:
print "a_lock is locked while this executes"

分配一个锁:allocate_lock() -> lock object (allocate() is an obsolute synonym)

操作锁的方法:

2) 线程相关的函数说明:

创建一个新线程:start_new_thread(function,args[,kwargs]) (start_new() is an obsolete synonym)

退出线程:exit()和exit_thread() (PyThread_exit_thread() is an obsolete synonym)

lock相关的函数使用演示样例(略去error):

import thread

def print_status(a_lock):
if a_lock.locked():
print "locked"
else:
print "not locked" a_lock = thread.allocate_lock()
print_status(a_lock)
a_lock.acquire()
print_status(a_lock)
a_lock.release()
print_status(a_lock)

thread相关的函数使用演示样例

import thread

def run(n):
# a back door, can not be run 4 times
if n == 4:
thread.exit()
for i in range(n):
print i thread.start_new_thread(run,(5,))

三 解决一个同步问题

试解决下面同步问题:使用两个线程交替输出“Hello”与“World”各5次。以“Hello”開始以“World”结束。

HelloWorld问题的同步模型建立:

semaphore h = 1, w = 0
# because the semaphore w is 0,so we should acquire the lock w to let it be zero(locked) when we use python to .
thread1()
{
while(true)
{
p(h)
do something;
v(w)
}
}
thread2()
{
while(true)
{
p(w)
do something;
v(h)
}
}

②使用Python实现上述同步模型,两个解决方式例如以下。

方案A用main线程和另一个线程来交替打印。

方案B使用除main线程外的另两个线程交替打印“Hello”与“World”。

import thread

def world():
for i in range(5):
w_lock.acquire() # i want to print world
print "world"
h_lock.release() # you can print hello now
w_lock.release() # main thread
print "use two threads to print hello&world" h_lock = thread.allocate_lock()
w_lock = thread.allocate_lock() w_lock.acquire(); # "print world" can not be started first
thread.start_new_thread(world,())
for i in range(5):
h_lock.acquire()
print "hello"
w_lock.release() # raw_input("finished")
import thread

def hello():
for i in range(5):
h_ok.acquire()
print "hello"
w_ok.release()
def world():
for i in range(5):
w_ok.acquire()
print "world"
h_ok.release() # main thread
print "use two threads to print hello&world"
h_ok = thread.allocate_lock()
w_ok = thread.allocate_lock()
w_ok.acquire()
thread.start_new_thread(hello,())
thread.start_new_thread(world,()) raw_input("finished") # !!it is necessary,in case main thread exit too early

多线程在python中的使用 thread的更多相关文章

  1. Python中的鸡肋多线程

    作者:DarrenChan陈驰链接:https://www.zhihu.com/question/23474039/answer/269526476来源:知乎著作权归作者所有.商业转载请联系作者获得授 ...

  2. python中的多进程与多线程(二)

    1.使用多线程可以有效利用CPU资源,线程享有相同的地址空间和内存,这些线程如果同时读写变量,导致互相干扰,就会产生并发问题,为了避免并发问题,绝不能让多个线程读取或写入相同的变量,因此python中 ...

  3. 通过编写聊天程序来熟悉python中多线程及socket的用法

    1.引言 Python中提供了丰富的开源库,方便开发者快速就搭建好自己所需要的应用程序.本文通过编写基于tcp/ip协议的通信程序来熟悉python中socket以及多线程的使用. 2.python中 ...

  4. 聊聊Python中的多进程和多线程

    今天,想谈一下Python中的进程和线程. 最近在学习Django的时候,涉及到了多进程和多线程的知识点,所以想着一下把Python中的这块知识进行总结,所以系统地学习了一遍,将知识梳理如下. 1. ...

  5. Python中使用多进程来实现并行处理的方法小结

    进程和线程是计算机软件领域里很重要的概念,进程和线程有区别,也有着密切的联系,先来辨析一下这两个概念: 1.定义 进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和 ...

  6. 【转】Python中的GIL、多进程和多线程

    转自:http://lesliezhu.github.io/public/2015-04-20-python-multi-process-thread.html 目录 1. GIL(Global In ...

  7. python中的多线程【转】

    转载自: http://c4fun.cn/blog/2014/05/06/python-threading/ python中关于多线程的操作可以使用thread和threading模块来实现,其中th ...

  8. 学习笔记--python中使用多进程、多线程加速文本预处理

    一.任务描述 最近尝试自行构建skip-gram模型训练word2vec词向量表.其中有一步需要统计各词汇的出现频率,截取出现频率最高的10000个词汇进行保留,形成常用词词典.对于这个问题,我建立了 ...

  9. Python中Queue模块及多线程使用

    Python的Queue模块提供一种适用于多线程编程的FIFO实现.它可用于在生产者(producer)和消费者(consumer)之间线程安全(thread-safe)地传递消息或其它数据,因此多个 ...

随机推荐

  1. 关于IDEA无法完整显示项目文件结构

    今天发现一个奇怪的问题,就是我从本地导入了文件,明明已经成功了,但是在我的项目结构里面就是不显示,然而点击目录, 又能打开相应的文件,如图所示: 其实这个打开的只是包文件,只需要如下图操作即可:

  2. uni-app 地图初用 map

    一.uni-app 地图初用 map 代码如下: <template> <view> <!-- <page-head :title="title" ...

  3. TI Code Composer Studio MSP430系列驱动源代码

    一.参考TI官网驱动源代码 安装打开Code Composer Studio,如下图所示,最近在调试MSP430G2533的AD,需要参考官网的底层驱动配置. 从Code Composer Studi ...

  4. java设计模式--事件监听器模式和观察者模式

    监听器模式:事件源经过事件的封装传给监听器,当事件源触发事件后,监听器接收到事件对象可以回调事件的方法 观察者模式:观察者(Observer)相当于事件监听者,被观察者(Observable)相当于事 ...

  5. azure云中 mount: wrong fs type, bad option, bad superblock on /dev/sdc1

    2016-01-30 mount失败问题解决 [root@mofficedb2 ~]# mount /dev/sdc /dta mount: you must specify the filesyst ...

  6. mongodb适用和不适用的应用场景

    近期考虑把订单历史数据从Oracle数据库迁移到Nosql数据库做历史数据查询和分析,一天千万级数据.打算使用mongodb数据库.使用nodejs做查询和统计API,对并发请求量要求低,不知道有没有 ...

  7. OCP-1Z0-051-题目解析-第26题

    26. Which is the valid CREATE TABLE statement? A. CREATE TABLE  emp9$#  (emp_no NUMBER (4));  B. CRE ...

  8. 下载eclipse详细步骤

    先登陆eclipse的官网 然后点击红色箭头进行选择你电脑是32还是64位的 根据自己的需求下载 然后点击下载 这里下载的是安装包,你要进行压缩.安装时一定要好相应的jdk要不然就会报错 这上面的错误 ...

  9. Android学习笔记进阶20 之得到图片的缩略图

    <1>简介 之前往往是通过Bitmap.Drawable和Canvas配合完成,需要写一系列繁杂的逻辑去缩小原有图片,从而得到缩略图. 现在我给大家介绍一种比较简单的方法:(网上有) 在A ...

  10. js插件---markdown如何使用

    js插件---markdown如何使用 一.总结 一句话总结:看文档,看api,看参数列表,看js调用插件的调用函数的参数(json) 1.js和css的问题:如何知道插件要引入哪些js和css? a ...