iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python多线程入门学习
  • 489
分享到

Python多线程入门学习

2024-04-02 19:04:59 489人浏览 安东尼

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

摘要

python 中使用线程有两种方式:函数或者用类来包装线程对象。 函数式: 调用 thread 模块中的start_new_thread()函数来产生新线程。 语法如下: thr

python 中使用线程有两种方式:函数或者用类来包装线程对象。

函数式:

调用 thread 模块中的start_new_thread()函数来产生新线程。

语法如下:


thread.start_new_thread(function, args[, kwargs])

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,它必须是个 tuple 类型。
  • kwargs - 可选参数。

import thread
import time
 
# 为线程定义一个函数
def print_time(threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % (threadName, time.ctime(time.time())))
 
# 创建两个线程
try:
   thread.start_new_thread(print_time, ("Thread-1", 2,))
   thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
   print ("Error: unable to start thread")
 
while 1:
   pass

使用 Threading 模块创建线程

使用 Threading模块创建线程,直接从 threading.Thread 继承,然后重写__init__方法和 run 方法:


import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
        print ("Starting " + self.name)
        print_time(self.name, self.counter, 5)
        print ("Exiting " + self.name)
 
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            (threading.Thread).exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
 
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
 
# 开启线程
thread1.start()
thread2.start()
 
print ("Exiting Main Thread")

线程同步

如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。

使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。如下:


import threading
import time
 
class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Starting " + self.name)
       # 获得,成功获得锁定后返回True
       # 可选的timeout参数不填时将一直阻塞直到获得锁定
       # 否则超时后将返回False
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 释放锁
        threadLock.release()
 
def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
 
threadLock = threading.Lock()
threads = []
 
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
 
# 开启新线程
thread1.start()
thread2.start()
 
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
 
# 等待所有线程完成
for t in threads:
    t.join()
print ("Exiting Main Thread")

线程优先级队列(Queue)

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括 FIFO(先入先出)队列 Queue,LIFO(后入先出)队列 LifoQueue 和优先级队列 PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。

Queue 模块中的常用方法:

  • Queue.qsize() 返回队列的大小
  • Queue.empty() 如果队列为空,返回True,反之False
  • Queue.full() 如果队列满了,返回True,反之False
  • Queue.full 与 maxsize 大小对应
  • Queue.get([block[, timeout]])获取队列,timeout等待时间
  • Queue.get_nowait() 相当Queue.get(False)
  • Queue.put(item) 写入队列,timeout等待时间
  • Queue.put_nowait(item) 相当Queue.put(item, False)
  • Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
  • Queue.join() 实际上意味着等到队列为空,再执行别的操作

import Queue
import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print ("Starting " + self.name)
        process_data(self.name, self.q)
        print ("Exiting " + self.name)
 
def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print ("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)
 
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
 
# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1
 
# 填充队列
queueLock.acquire()
for Word in nameList:
    workQueue.put(word)
queueLock.release()
 
# 等待队列清空
while not workQueue.empty():
    pass
 
# 通知线程是时候退出
exitFlag = 1
 
# 等待所有线程完成
for t in threads:
    t.join()
print ("Exiting Main Thread")

到此这篇关于Python多线程入门学习的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: Python多线程入门学习

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

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

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

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

下载Word文档
猜你喜欢
  • Python多线程入门学习
    Python 中使用线程有两种方式:函数或者用类来包装线程对象。 函数式: 调用 thread 模块中的start_new_thread()函数来产生新线程。 语法如下: thr...
    99+
    2024-04-02
  • Python入门学习路线
    Python技术路径中包含入门知识、Python基础、Web框架、基础项目、网络编程、数据与计算、综合项目七个模块。路径中的教程将带你逐步深入,学会如何使用 Python 实现一个博客,桌面词典,微信机器人或网络安全软件等。完成本路径的基...
    99+
    2023-01-30
    入门 路线 Python
  • C#多线程学习之基础入门
    目录同步方式异步多线程方式异步多线程优化异步回调异步信号量异步多线程返回值异步多线程返回值回调线程(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进...
    99+
    2024-04-02
  • python多线程学习
    python多线程学习:python中的线程使用的两种方式:函数或者用类来包装线程对象。1、函数式:调用thread模块中start_new_thread()函数来产生新线程。#!/usr/bin/env python #coding:ut...
    99+
    2023-01-31
    多线程 python
  • python入门学习
    首先在官网下载好python3.6及以上的版本,根据自己的系统选择:没有显示64位的就是32位的安装包,选择蓝线的能够直接打开 在控制台输入python,配置成功的图片如下: 从IDLE打开python输入指令 print("I lo...
    99+
    2023-01-31
    入门 python
  • 深入学习C#多线程
    目录一、基本概念1、进程2、线程二、多线程2.1System.Threading.Thread类2.2 线程的常用属性2.2.1线程的标识符2.2.2线程的优先级别2.2....
    99+
    2024-04-02
  • Python多线程学习 setDae
    (2)setDaemon方法: # -*- coding: utf-8 -*- import threading import time class myThread(threading.Thread):     def __init...
    99+
    2023-01-31
    多线程 Python setDae
  • 好程序员Python学习路线之python爬虫入门
      好程序员Python学习路线之python爬虫入门,随着网络的迅速发展,万维网成为大量信息的载体,如何有效地提取并利用这些信息成为一个巨大的挑战。搜索引擎(Search Engine),例如传统的通用搜索引擎AltaVista,Yaho...
    99+
    2023-06-02
  • 2019最全Python入门学习路线,绝
    近几年Python的受欢迎程度可谓是扶摇直上,当然了学习的人也是愈来愈多。一些学习Python的小白在学习初期,总希望能够得到一份Python学习路线图,小编经过多方汇总为大家汇总了一份Python学习路线图。 对于一个零基础的想学习pyt...
    99+
    2023-01-31
    最全 入门 路线
  • Python入门学习(六)
    在熟悉了Python中常用的一些内置函数, 那接下来我们定义一个自己的函数吧 def add(x, y): return x + y 函数 函数语法 def functonname(parameters): ... ...
    99+
    2023-01-31
    入门 Python
  • Python基础学习教程_Python学习路线_我是Python小白,怎么入门Python
    Python基础学习教程_Python学习路线_我是Python小白,怎么入门Python人生苦短,我用Python!!!短短几个字,现在在各大编程学习类平台随处可见,短短几个字,足以见Python今日的地位!为什么Python总被提起,为...
    99+
    2023-06-02
  • Python学习入门基础教程(learn
     在Python里可以自定义函数,实现某特定功能,这里首先要区分一下函数的定义和函数的调用两个基本概念,初学者往往容易混淆。      函数的定义是指将一堆能实现特定功能的语句用一个函数名标识起来,而函数的调用则是通过函数名来使用这一堆语句...
    99+
    2023-01-31
    基础教程 入门 Python
  • Python 入门学习笔记
    1 安装Anaconda和jupyter notebook   之前没有听说过这两个名词,然后看完介绍,按照我自己的理解,Anaconda是一个集合很多环境和模块的存储地方。 Jupyter notebook 就是一个可以在此环境里打代码...
    99+
    2023-01-30
    学习笔记 入门 Python
  • Python学习入门基础教程(lear
      在if分支判断语句里的条件判断语句不一定就是一个表达式,可以是多个(布尔)表达式的组合关系运算,这里如何使用更多的关系表达式构建出一个比较复杂的条件判断呢?这里需要再了解一下逻辑运算的基础知识。逻辑关系运算有以下几种运算符.     ...
    99+
    2023-01-31
    基础教程 入门 Python
  • Python入门学习之operator-
    本模块主要包括一些Python内部操作符对应的函数。这些函数主要分为几类:对象比较、逻辑比较、算术运算和序列操作。 操作  语法 函数 相加 a + b  add(a, b) 字符串拼接 ...
    99+
    2023-01-31
    入门 Python operator
  • Python基础学习入门
    Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。在命令行窗口输入"python" 命令来查看本地是否已经安装Python以及Python的安装版本Python下载Python官网:http://www...
    99+
    2023-06-02
  • Python多线程编程入门详解
    目录一、任务、进程和线程任务进程线程进程和线程的关系二、Python既支持多进程,又支持多线程Python实现多进程Process进程类的说明Python实现多线程线程类Thread...
    99+
    2024-04-02
  • python爬虫入门八:多进程/多线程
    引用虫师的解释: 计算机程序只不过是磁盘中可执行的,二进制(或其它类型)的数据。它们只有在被读取到内存中,被操作系统调用的时候才开始它们的生命期。 进程(有时被称为重量级进程)是程序的一次执行。每个进程都有自己的地址空间,内存,数据栈...
    99+
    2023-01-30
    爬虫 多线程 入门
  • Python学习记录-多进程和多线程
    [TOC] 1. 进程和线程 进程 狭义定义:进程是正在运行的程序的实例(an instance of a computer program that is being executed)。广义定义:进程是一个具有一定独立功能的程序关于某...
    99+
    2023-01-31
    多线程 进程 Python
  • 学习java多线程
    目录介绍为什么需要多线程线程状态转换线程使用方式继承 Thread 类实现 Runnable 接口实现 Callable 接口同步代码---Runnable接口方式同步方法--Run...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作