iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python—多线程
  • 567
分享到

python—多线程

多线程python 2023-01-31 07:01:07 567人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

一、多线程实例  线程时应用程序中工作的最小单位,python中提供了threading模块来对多线程操作,一般多核cpu采用多进程方式,单核才采用多线程方式  方法:  将要执行的方法threading.Thread作为参数传给构造方法(

一、多线程实例

  线程时应用程序中工作的最小单位,python中提供了threading模块来对多线程操作,一般多核cpu采用多进程方式,单核才采用多线程方式

  方法:

  将要执行的方法threading.Thread作为参数传给构造方法(和多进程类似),格式如下:

  t = threading.Thread(target=action,args=(i,))


例子:

import threading

def worker(n):
    print("start worker{0}".fORMat(n))
    
class Mythread(threading.Thread):
    def __init__(self,args):
        super(Mythread,self).__init__() # super(Mythread,self)超类,将类接收到的参数threading.Thread,传给构造函数,最后赋值给self.args,便于类中其他函数调用
        self.args = args
        
    def run(self):
        print("start Mythread {0}".format(self.args))
        
if __name__ == "__main__":
    for i in range(1,6):
        t1 = threading.Thread(target=worker,args=(i,))
        t1.start()
    t1.join()
    
    for x in range(6,11):
        t2 = Mythread(x)
        t2.start()
    t2.join()

运行结果:

start worker1

start worker2

start worker3

start worker4

start worker5

start Mythread 6

start Mythread 7

start Mythread 8

start Mythread 9

start Mythread 10



扩展:super()方法的语法: super(type[, object-or-type]);type -- 类名,object-or-type --对象或类型,一般为self

例子:

class Parent(object):
   def __init__(self):
       self.parent = "Good"
       print ('Parent')
   def identity(self, message):
       print ("%s I'm parent" % message)
       
class Child(Parent):
   def __init__(self):
       super(Child, self).__init__()  #首先找到Child的父类(Parent),然后把类Child的对象转换为类Parent的对象,调用父类的构造函数__init__()
       print ('Child')
       print("******"*4)
       
   def identity(self, message):
       super(Child, self).identity(message) #首先找到Child的父类(Parent),然后把类Child的对象转换为类Parent的对象,调用父类的identity(message)函数
       print ("I'm child")
       print("******" * 4)
       print (self.parent)
       
if __name__ == '__main__':
   Test = Child()
   Test.identity('hello China')

运行结果:

Parent

Child

************************

hello China I'm parent

I'm child

************************

Good



二、线程锁

  通过threading.Lock()来创建,函数在执行前先获得锁,执行后释放锁,和进程锁相似

  with lock:

  或者

  lock.acquire()  #先获得锁

  ...

  lock.release()  #执行完,释放锁


例子:

import threading
import time
def worker(name,lock):
    with lock:   
        print("start {0}".format(name))
        time.sleep(3)
        print("end {0}".format(name))
        
if __name__ == "__main__":
    lock = threading.Lock()  
    t1 = threading.Thread(target=worker,args=("worker1",lock))
    t2 = threading.Thread(target=worker,args=("worker2", lock))
    
    t1.start()
    t2.start()
    print ("main end")

运行结果:

start worker1

main end

end worker1

start worker2

end worker2

说明:只有线程1结束以后,线程2才能执行



三、线程共享变量

  多线程和多进程不同之处在于多线程本身就是可以和父进程进行共享内存的,这也是为什么其中一个线程挂掉之后,其他线程也死掉的原因


例子:

import threading
def worker(l):
    l.append("hello")
    l.append("china")
    l.append("world")
    
if __name__ == "__main__":
    l = list()
    l += range(1,5)
    print(l)
    
    t = threading.Thread(target=worker,args=(l,))
    t.start()
    print(l)


运行结果:

[1, 2, 3, 4]

[1, 2, 3, 4, 'hello', 'china', 'world']


--结束END--

本文标题: python—多线程

本文链接: https://www.lsjlt.com/news/191112.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python多线程————3、多线程间通
    1、共享变量 #通过共享变量 import time import threading url_list = [] def get_detail_html(): global url_list while True: ...
    99+
    2023-01-31
    多线程 python
  • Python 多线程
      文章来源:https://www.runoob.com/python/python-multithreading.html 多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的...
    99+
    2023-01-31
    多线程 Python
  • python多线程
    Python 多线程 多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的...
    99+
    2023-01-30
    多线程 python
  • python—多线程
    一、多线程实例  线程时应用程序中工作的最小单位,python中提供了threading模块来对多线程操作,一般多核cpu采用多进程方式,单核才采用多线程方式  方法:  将要执行的方法threading.Thread作为参数传给构造方法(...
    99+
    2023-01-31
    多线程 python
  • Python多线程编程,线程锁
    多线程threading 模块创建线程创建自己的线程类线程通信线程同步互斥方法线程锁@需要了解!!!   什么是线程? 线程也是一种多任务的编程方法,可以利用计算机多核资源完成程序的并发运行。 线程又被称为轻量级进程 ...
    99+
    2023-01-30
    线程 多线程 Python
  • python多线程socket编程--多
    Python中实现socket通信的服务端比较复杂,而客户端非常简单,所以客户端基本上都是用sockct模块实现,而服务 端用有很多模块可以使用,如下: 1、客户端 #!/usr/bin/env python #coding...
    99+
    2023-01-31
    多线程 python socket
  • Python多线程编程
      一个串行程序需要从每个I/O终端通道来检测用户的输入,然而程序在读取过程中不能阻塞,因为用户输入的到达时间的不确定,并且阻塞会妨碍其他I/O通道的处理。由于串行程序只有唯一的执行线程,因此它需要兼顾执行的多个任务,确保其中的某个任务不会...
    99+
    2023-01-31
    多线程 Python
  • python 多线程编程
    使用回调方式 import time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep...
    99+
    2023-01-31
    多线程 python
  • python多线程-Semaphore(
    Semaphore(value=1) Semaphore对象内部管理一个计数器,该计数器由每个acquire()调用递减,并由每个release()调用递增。计数器永远不会低于零,当acquire()发现计数器为零时,线程阻塞,等待其他线...
    99+
    2023-01-30
    多线程 python Semaphore
  • python 多线程+queue
    python的queue设计的是线程安全的,所以大家伙放心用吧! python多线程的一种简单的实现如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import threadi...
    99+
    2023-01-31
    多线程 python queue
  • python多线程threading
    本文通过 4个example 介绍python中多线程package —— threading的常用用法, 包括调用多线程, 同步队列类Queue, Ctrl+c结束多线程。 example1. 调用10个线程, 分别打印0~...
    99+
    2023-01-31
    多线程 python threading
  • Python 多线程 multithr
    【Python】python 多线程两种实现方式 目前python提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对threa...
    99+
    2023-01-31
    多线程 Python multithr
  • python之多线程
    一、threading 模块 multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性 二、开启线程的两种方式 from threading import Thread import ti...
    99+
    2023-01-30
    之多 线程 python
  • python threadpool多线程
            在写爬虫下载一个网页中的多个链接文件时(http://blog.sina.com.cn/s/blog_740773f40100ywyg.html  ),使用多线程会提高下载速度。         使用线程池能够简单的解决这...
    99+
    2023-01-31
    多线程 python threadpool
  • python多线程paramiko
    初学python,网上找发些关于paramiko实现python多线程的功能,发现相互抄袭占多.别人的总归是别人的,也同时为了练习技术,就自己写了一个基于paramiko免密认证多线程并发脚本.与大家共勉.使用上的问题的同学也可以联系我.刚...
    99+
    2023-01-31
    多线程 python paramiko
  • Python 多线程 threadin
    #!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'gaogd' ''' ### 多进程 import threading import time def run(num)...
    99+
    2023-01-31
    多线程 Python threadin
  • python的多线程
    python多线程 一、线程的概念 线程是CPU分配资源的基本单位。当一程序开始运行,这个程序就变成了一个进程,而一个进程相当于一个或者多个线程。当没有多线程编程时,一个进程相当于一个主线程;当有多线...
    99+
    2023-09-01
    python 开发语言 pycharm
  • python socket多线程和多进程
    在socket中,如果直接创建的话,是只能接受一个用户的请求需要实现socketserver中的handle方法,可以实现多进程并发访问 SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理...
    99+
    2023-01-31
    多线程 进程 python
  • python之多线程与多进程
    1. 多进程与多线程 (1)背景:为何需要多进程或者多线程:在同一时间里,同一个计算机系统中如果允许两个或者两个以上的进程处于运行状态,这便是多任务。多任务会带来的好处例如用户边听歌、边上网、边打印,而这些任务之间丝毫不会互相干扰。使用多...
    99+
    2023-01-31
    之多 线程 进程
  • python多线程和多进程(二)
    ---恢复内容开始--- 一、多进程   1、multiprocessing模块用来开启子进程,并在子进程中执行我们定制的任务(比如函数),该模块与多线程模块threading的编程接口类似。 import time from mult...
    99+
    2023-01-30
    多线程 进程 python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作