美文网首页
python多线程

python多线程

作者: ayusong870 | 来源:发表于2020-03-24 16:23 被阅读0次

1. threading.Thread

方法一:Thread类

Python的多线程Thread,有一个弊端,其多线程Thread是在一个python虚拟机下运行的,也就是说,无论多少个线程,都是在一个核内运行。

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        #其他
def run(self):
    while(conditions):
        #代码
Mt = MyThread()
Mt.start()#启动线程

Python的多线程没有强制停止,只能在conditions中增加手动停止的边界条件。

方法二:简单多线程

import threading
from time import ctime,sleep

def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(func,ctime())
        sleep(5)

threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)

for t in threads:
    t.setDaemon(True)
    t.start()

print "all over %s" %ctime()

守护线程

setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。
The entire Python program exits when no alive non-daemon threads are left
上面这句话的意思是:当没有存活的非守护进程时,整个python程序才会退出。
也就是说:如果主线程执行完以后,还有其他非守护线程,主线程是不会退出的,会被无限挂起;必须将线程声明为守护线程之后,如果队列中的数据运行完了,那么整个程序想什么时候退出就退出,不用等待。

相关文章

  • GIL

    谈谈python的GIL、多线程、多进程 最近在看 Python 的多线程,经常我们会听到老手说:“python下...

  • Python多线程编程——多线程编程中的加锁机制

    如果大家对Python中的多线程编程不是很了解,推荐大家阅读之前的两篇文章:Python多线程编程——多线程基础介...

  • 5-线程(补充)

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python_提高

    GIL全局解释器锁 描述Python GIL的概念, 以及它对python多线程的影响?编写⼀个 多线程抓取⽹⻚的...

  • Python程序员都知道的入门知识の八

    目录【Python程序员都知道的入门知识】 1. 多线程threading、Queue Python的多线程由th...

  • Python多线程实现生产者消费者

    1. Python多线程介绍 Python提供了两个有关多线程的标准库,thread和threading。thre...

  • 多线程

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python多线程(上)

    前言 说起Python的多线程,很多人都嗤之以鼻,说Python的多线程是假的多线程,没有用,或者说不好用,那本次...

  • Python 3中的多线程

    Python 3的多线程 Python 3的多线程模块threading在旧版_thread模块基础上进行了更高层...

  • Python 多线程抓取图片效率实验

    Python 多线程抓取图片效率实验 实验目的: 是学习python 多线程的工作原理,及通过抓取400张图片这种...

网友评论

      本文标题:python多线程

      本文链接:https://www.haomeiwen.com/subject/edwcrhtx.html