threading 常见用法:

(1) 在 thread 中,我们是通过 thread.start_new_thread(function, args) 来开启一个线程,接收一个函数和该函数的参数,函数的参数必须是元组的形式
(2) 在 threading 中,我们是通过 threading.Thread(target=function, args=(....)) 来创建一个对象,然后再通过对象的 start() 方法来开启一个线程,多个线程可以并发执行

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
print time.ctime()
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=()) # 创建一个 Thread 对象,接收一个函数和该函数的参数
t.start() # 通过对象来开启一个新的线程,通过线程来执行函数
[root@localhost ~]$ python 1.py    # 多个线程并发执行,只需要执行一秒
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019

threading 有两种方法可以开启一个新的线程:

(1) 如上面的例子,通过创建 Thread 对象,然后通过对象的 start() 方法来运行一个新的线程
(2) 第二种方法是继承 threading.Thread 这个类, 然后重写 run() 方法来运行一个新的线程

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading class MyThread(threading.Thread): def __init__(self):
threading.Thread.__init__(self) def run(self):
print time.ctime()
time.sleep(1) for i in range(3):
t = MyThread()
t.start()
[root@localhost ~]$ python 1.py
Mon Jan 28 23:53:02 2019
Mon Jan 28 23:53:02 2019
Mon Jan 28 23:53:02 2019

threading.Lock():用于创建一个锁对象,我们可以同时开启多个线程,但是在任意时刻只能有一个线程能在解释器运行,因此需要由全局解锁器(GIL)控制运行哪个线程

锁对象的常用方法如下:

lock = threading.Lock() 创建一个锁对象
    lock.acquire() 锁上锁,当某个线程被锁上之后,会优先执行这个锁的内容,直到锁释放才会执行其他线程
    lock.locked() 查看锁的状态,如果已经被锁上了则返回True,否则返回False
    lock.release() 释放锁,必须先获得锁才能释放锁

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def hello():
for i in range(3):
hello_lock.acquire()
print('hello'),
time.sleep(1)
world_lock.release() def world():
for i in range(3):
world_lock.acquire()
print('world')
time.sleep(1)
hello_lock.release() hello_lock = threading.Lock()
world_lock = threading.Lock() world_lock.acquire()
t1 = threading.Thread(target=hello, args=())
t2 = threading.Thread(target=world, args=()) t1.start()
t2.start()
[root@localhost ~]$ python 1.py
hello world
hello world
hello world

其他常用方法:

t.join()方法用于阻塞下一个线程的运行,等待当前线程执行完再执行下一个线程,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
print time.ctime()
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=())
t.start()
t.join()
[root@localhost ~]$ python 1.py     # 由于线程被阻塞,需要执行3秒
Mon Jan 28 21:33:35 2019
Mon Jan 28 21:33:36 2019
Mon Jan 28 21:33:37 2019

t.setDaemon()方法用于设置当前线程随着主线程的退出而退出,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun(): # 函数的功能是打印三次当前时间
for i in range(3):
print time.ctime()
time.sleep(1) t = threading.Thread(target=fun, args=())
t.setDaemon(True)
t.start() print 'End...' # 执行 print 之后,主线程就退出了,最终结果只会打印一次
[root@localhost ~]$ python 1.py
Mon Jan 28 21:54:48 2019
End...

t.getName() 用于获取线程的名字,t.setName() 用于重新设置线程的名字,默认的线程名是 Thread-1,Thread-2,Thread-3,......

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
newName = 'new-' + t.getName()
print newName
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=())
t.start()
[root@localhost ~]$ python 1.py
new-Thread-1
new-Thread-2
new-Thread-3

多线程模块:threading的更多相关文章

  1. 基于Python的多线程模块Threading小结

    步入正题前,先准备下基本知识,线程与进程的概念. 相信作为一个测试人员,如果从理论概念上来说其两者的概念或者区别,估计只会一脸蒙蔽,这里就举个例子来说明下其中的相关概念. 平安夜刚过,你是吃到了苹果还 ...

  2. Python并发复习2 - 多线程模块threading

    一.多线程的调用 threading 模块建立在thread 模块之上.thread模块以低级.原始的方式来处理和控制线程,而threading 模块通过对thread进行二次封装, 提供了更方便的a ...

  3. 用生动的案例一步步带你学会python多线程模块

    鱼和熊掌不可兼得 鱼,我所欲也,熊掌,亦我所欲也,二者不可得兼,舍鱼而取熊掌者也. 从6月开始写公众号,连着四个月一直尽量保证一周五更,结果整天熬夜搞的身体素质骤降.十一休假决定暂时将公众号放放,好好 ...

  4. python笔记9 线程进程 threading多线程模块 GIL锁 multiprocessing多进程模块 同步锁Lock 队列queue IO模型

    线程与进程 进程 进程就是一个程序在一个数据集上的一次动态执行过程.进程一般由程序.数据集.进程控制块三部分组成.我们编写的程序用来描述进程要完成哪些功能以及如何完成:数据集则是程序在执行过程中所需要 ...

  5. python-网络安全编程第六天(threading多线程模块&Queue模块&subprocess模块)

    前言 昨天晚上9点多就睡了 2点起来没睡意... 那就学习吧emmmm ,拿起闲置几天的python课程学习.学习到现在5.58了 总结下 继续开始学习新的内容 多多线程? 线程(英语:thread) ...

  6. Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

    Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fab ...

  7. Python线程模块threading

    线程,程序执行的最小单元,单线程处理多个任务只能一个处理完后继续处理下一个直到全部处理完,多线程处理任务会比单线程处理起来快吗?在python程序里得看情况,首先有GIL锁的存在导致同一时刻只能有一个 ...

  8. Python多线程模块

    引言 thread threading 1 Thread 11 下面使用threading模块实现与上面相同的功能 12 在创建新线程时还可以给Thread传递可调用类的对象这样使用类本身来保存信息 ...

  9. 多线程模块的同步机制event对象

    多线程模块的同步机制event对象 线程的核心特征就是他们能够以非确定的方式(即何时开始执行,何时被打断,何时恢复完全由操作系统来调度管理,这是用户和程序员无法确定的)独立执行的,如果程序中有其他线程 ...

  10. Python的多线程(threading)与多进程(multiprocessing )

    进程:程序的一次执行(程序载入内存,系统分配资源运行).每个进程有自己的内存空间,数据栈等,进程之间可以进行通讯,但是不能共享信息. 线程:所有的线程运行在同一个进程中,共享相同的运行环境.每个独立的 ...

随机推荐

  1. 解决 windows10和ubuntu16.04双系统下时间不对的问题

  2. java图片截取组件ImageIO

    引用:http://blog.csdn.net/cdl2008sky/article/details/7775681 javax.imageio使用 ImageIO 类的静态方法可以执行许多常见的图像 ...

  3. ios的一些经验记录2

    1.UITextField 的事件用 valuechanged outlet连接 2.swift 中 struct 和class的self 3.Int 和UInt 4.Gesture 的target ...

  4. VS2008 express + opencv配置

    刚开始接触opencv,不是很熟悉,配置过程主要参考了这篇博客,大家可以去看看 http://www.cnblogs.com/micky-zhou/archive/2012/08/06/2624433 ...

  5. 完美解决方案:wordpress后台进不去,用户名、密码输入了登陆没有反应(有更新)

    http://mingming4745.blog.163.com/blog/static/173845720119159425890/?suggestedreading ——————————————— ...

  6. Laravel 多where组合

    $model=DB::table("user"); foreach($request as $value){ if($value->name){ $model->whe ...

  7. 支付宝前端开源框架Alice(解决各个浏览器的样式不一致的问题)

    /**************** 网址:https://github.com/sofish/Alice /******************       @charset "utf-8& ...

  8. 【转】MFC CreateFont 用法

    中国人自古就有自右至左.从上到下书写汉字的习惯.而当我们在自己所编写的应用程序中使用输出函数输出的总是自左至右的横排文字.有没有可能在我们的应用程序中实现竖写汉字的效果呢?笔者偶然发现了一种利用VC实 ...

  9. 静态变量加前缀 s_(表示 static)

    静态变量加前缀 s_(表示 static). 例如: void Init(…) { static int s_initValue; // 静态变量 … } #include <iostream& ...

  10. 关于document.createDocumentFragment()(转)

    documentFragment 是一个无父对象的document对象. 他支持以下DOM2方法: appendChild, cloneNode, hasAttributes, hasChildNod ...