Python通过两个标准库(thread, threading)提供了对多线程的支持

thread模块

import time
import thread  

def runner(arg):
    for i in range(6):
        print str(i)+':'+arg  

        time.sleep(1)
    #结束当前线程
    thread.exit_thread()  #等同于thread.exit()  

#启动一个线程,第一个参数为函数名,
#第二个参数为一个tuple类型,是传给函数的参数
thread.start_new_thread(runner, ('hello world',))   #等同于thread.start_new(runner, ('hello world'))  

#创建一个锁,锁用于线程同步,通常控制对共享资源的访问
lock = thread.allocate_lock()  #等同于thread.allocate()
num = 0
#获得锁,成功返回True,失败返回False
if lock.acquire():
    num += 1
    #释放锁
    lock.release()
#thread模块提供的线程都将在主线程结束后同时结束,因此将主线程延迟结束
time.sleep(10)
print 'num:'+str(num)  

threading.Thread类的常用方法

1.在自己的线程类的__ init__里调用threading.Thread.__init__(self,name=threadname)threadname为线程的名字。
2.run(),通常需要重写,编写代码实现做需要的功能。
3.getName(),获得线程对象名称。
4.setName(),设置线程对象名称。
5.start(),启动线程。
6.join([timeout]),等待另一线程结束后再运行。
7.setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
8.isDaemon(),判断线程是否随主线程一起结束。
9.isAlive(),检查线程是否在运行中。

要想创建一个线程对象,只要继承类threading.Thread,然后在__ init__里边调用threading.Thread.__init__()方法即可。重写run()方法,将要实现的功能放到此方法中即可。

class runner(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.thread_stop = False
    def run(self):
        while not self.thread_stop:
            print str(self.name)+':'+'hello world'
            time.sleep(1)
    def stop(self):
        self.thread_stop = True  

def test():
    t = runner('thread')
    t.start()
    time.sleep(10)
    t.stop()  

if __name__ == '__main__':
    test()  

线程同步(锁)

最简单的同步机制就是锁。锁对象由threading.RLock类创建。线程可以使用锁的acquire()方法获得锁,这样锁就进入locked状态。每次只有一个线程可以获得锁。如果当另一个线程试图获得这个锁的时候,就会被系统变为blocked状态,直到那个拥有锁的线程调用锁的release()方法来释放锁,这样锁就会进入unlocked状态。blocked状态的线程就会收到一个通知,并有权利获得锁。

如果多个线程处于blocked状态,所有线程都会先解除blocked状态,然后系统选择一个线程来获得锁,其他的线程继续blocked。python的threading module是在建立在thread module基础之上的一个module,在thread module中,python提供了用户级的线程同步工具Lock对象。

而在threading module中,python又提供了Lock对象的变种: RLock对象。RLock对象内部维护着一个Lock对象,它是一种可重入的对象。对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么由于第一次acquire之后没有release,第二次acquire将挂起线程。这会导致Lock对象永远不会release,使得线程死锁。

RLock对象允许一个线程多次对其进行acquire操作,因为在其内部通过一个counter变量维护着线程acquire的次数。而且每一次的acquire操作必须有一个release操作与之对应,在所有的release操作完成之后,别的线程才能申请该RLock对象。

我们把修改共享数据的代码称为临界区。必须将所有临界区都封闭在同一个锁对象的acquirerelease之间。

import time
import threading
num=0
lock = threading.RLock()
class runner(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name  

    def run(self):
        global num
        while True:
            if num >= 6: break
            if lock.acquire():
                print "Thread(%s) locked, Number: %d" % (self.name, num)
                time.sleep(1)
            lock.release()
            print "Thread(%s) released, Number: %d" % (self.name, num)
            time.sleep(1)
            num += 1   

def test():
    t1 = runner('thread1')
    t2 = runner('thread2')
    t1.start()
    t2.start()  

if __name__== '__main__':
    test()    

Python thread实现多线程

#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
  global count, mutex
  # 获得线程名
  threadname = threading.currentThread().getName()

  for x in xrange(0, int(a)):
    # 取得锁
    mutex.acquire()
    count = count + 1
    # 释放锁
    mutex.release()
    print threadname, x, count
    time.sleep(1)

def main(num):
  global count, mutex
  threads = []

  count = 1
  # 创建一个锁
  mutex = threading.Lock()
  # 先创建线程对象
  for x in xrange(0, num):
    threads.append(threading.Thread(target=thread_main, args=(10,)))
  # 启动所有线程
  for t in threads:
    t.start()
  # 主线程中等待所有子线程退出
  for t in threads:
    t.join() 

if __name__ == '__main__':
  num = 4
  # 创建4个线程
  main(4)

Python threading实现多线程

#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
  def __init__(self, num):
    threading.Thread.__init__(self)
    self._run_num = num

  def run(self):
    global count, mutex
    threadname = threading.currentThread().getName()

    for x in xrange(0, int(self._run_num)):
      mutex.acquire()
      count = count + 1
      mutex.release()
      print threadname, x, count
      time.sleep(1)

if __name__ == '__main__':
  global count, mutex
  threads = []
  num = 4
  count = 1
  # 创建锁
  mutex = threading.Lock()
  # 创建线程对象
  for x in xrange(0, num):
    threads.append(Test(10))
  # 启动线程
  for t in threads:
    t.start()
  # 等待子线程结束
  for t in threads:
    t.join() 

[python]多线程模块thread与threading的更多相关文章

  1. python进阶笔记 thread 和 threading模块学习

    Python通过两个标准库thread和threading提供对线程的支持.thread提供了低级别的.原始的线程以及一个简单的锁.threading基于Java的线程模型设计.锁(Lock)和条件变 ...

  2. Python多线程模块

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

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

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

  4. 利用python多线程模块实现模拟接口并发

    import requestsimport jsonimport threadingimport timeimport uuid class postrequests(): def __init__( ...

  5. python 多线程,tthread模块比较底层,而threading模块是对thread做了一些包装,multithreading

    Python多线程详解 2016/05/10 · 基础知识 · 1 评论· 多线程 分享到:20 本文作者: 伯乐在线 - 王海波 .未经作者许可,禁止转载!欢迎加入伯乐在线 专栏作者. 1.多线程的 ...

  6. python threading模块使用 以及python多线程操作的实践(使用Queue队列模块)

    今天花了近乎一天的时间研究python关于多线程的问题,查看了大量源码 自己也实践了一个生产消费者模型,所以把一天的收获总结一下. 由于GIL(Global Interpreter Lock)锁的关系 ...

  7. Python线程模块threading

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

  8. python 多线程学习

    多线程(multithreaded,MT),是指从软件或者硬件上实现多个线程并发执行的技术 什么是进程? 计算机程序只不过是磁盘中可执行的二进制(或其他类型)的数据.它们只有在被读取到内存中,被操作系 ...

  9. Python多线程及其使用方法

    [Python之旅]第六篇(三):Python多线程及其使用方法   python 多线程 多线程使用方法 GIL 摘要: 1.Python中的多线程     执行一个程序,即在操作系统中开启了一个进 ...

随机推荐

  1. 记——加快gradle 构建速度的经验

    Gradle作为一个新的构建系统,无疑在灵活,扩展,跨平台等各方面都表现得非常优秀,然而,它也有一点备受吐槽,就是速度慢.以下为本人使用gradle过程中,几次加快gradle构建速度的经验之谈. 本 ...

  2. Win10家庭版中的SQL2005无法远程连接

    最近公司重新更换了电脑,电脑自事Win10家庭版本.在安装开发工具中发现有不少的问题,如无法安装SQL Server 2005,无法安装VS2013等.最终通过网上寻找安装SQL Server 200 ...

  3. IIS服务器如何抗住高并发的客户端访问

    今天被问到一个问题,如果你在阿里云上部署了一个IIS服务器,此时如果有成千上万的客户端来访问,你将如何设计?我东扯扯西谈谈,说加个线程池来处理,在加个请求队列.当时觉得说的没有问题,现在想想,服务器自 ...

  4. CALayer的属性和使用

    一.CALayer的常用属性 1.@propertyCGPoint position; 图层中心点的位置,类似与UIView的center:用来设置CALayer在父层中的位置:以父层的左上角为原点( ...

  5. svn 不能添加.a文件

    1.打开终端输入    open ~/.subversion/ 2.双击打开config文件 3.修改如下两行 # global-ignores = *.o *.lo *.la *.al .libs ...

  6. List集合中元素排序

    应用场景: 在开发中经常遇到要对List<Object>集合进行排序,并且是根据集合中的对象的某个属性来进行排序    --------以下就此做出的解决方案 public static ...

  7. 交换机设置IP

    二成交换机所有端口在默认情况下都是属于vlan1的 代表整个交换机 你只需要设置vlan1的ip地址就行了 进入交换机配置界面后 命令如下:enableconfigure terminalinterf ...

  8. py-oauth2包使用简记

    接前两天线上项目py2升级py3的书,老廖的一个旧库snspy,他已经不维护了,用的api又比较久,不好升级,最后速度找了个OAuth库取代了它,由于时间紧张,直接在pypi上搜索了一下,找到这个支持 ...

  9. 任务调度利器:Celery

    http://www.liaoxuefeng.com/article/00137760323922531a8582c08814fb09e9930cede45e3cc000 Celery是Python开 ...

  10. gitlab钩子搭建

    目标:在本地开发机上push代码到GitLab仓库时,通过钩子同步到测试服务器 准备工作GitLab 服务器一台测试服务器一台本地开发服务器一台 1.在gitlab上新建一个项目,名称test2.在本 ...