python基础线程-管理并发线程

python_进程与线程_多线程 进程池:创建一个进程池,并设置进程池中最大的进程数量。假设进程池中的最大进程数为3,现在有10个任务需要执行,那么进程池一次可以执行3个任务,4次即可完成全部任务的执行。线程是CPU可执行的最小单位,被包含在进程中,是进程中实际的运行单位。kwargs:用字典以关键字参数的形式传入target对应函数的参数。kwargs:表示调用函数的关键字参数,以字典的形式进行传递。args:用元祖以位置参数的形式传入targt对应函数的参数。args:表示调用的函数的位置参数,以元组的形式进行传递。 阅读详情

线程模块建立在线程的底层特性之上,使线程的工作变得更简单、更像python。使用线程允许程序在同一进程空间中并发运行多个操作。

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:961562169

线程对象

使用线程最简单的方法是用目标函数实例化它,然后调用start()让它开始工作。

import threading

def worker():
    """线程worker函数"""
    print('Worker')
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

结果:输出为五行,每行上都有“Worker”

$ python3 threading_simple.py

Worker
Worker
Worker
Worker
Worker

能够生成一个线程并传递参数来告诉它要做什么工作是很有用的。这个例子传递一个数字,然后线程打印这个数字。

import threading

def worker(num):
    """线程worker函数"""
    print('Worker: {num}' )
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

现在每个线程打印的消息包含一个数字:

$ python3 -u threading_simpleargs.py

Worker: 0
Worker: 1
Worker: 2
Worker: 3
Worker: 4

确定当前线程

使用参数来标识或命名线程很麻烦,而且没有必要。每个Thread实例都有一个具有默认值的名称,该名字可以在创建线程时更改。命名线程在具有多个服务线程来处理不同操作的服务器进程中很有用。

import threading
import time

def worker():
    print(threading.currentThread().getName(), '开始运行')
    time.sleep(2)
    print(threading.currentThread().getName(), '结束运行')

def my_service():
    print(threading.currentThread().getName(), '开始运行')
    time.sleep(3)
    print(threading.currentThread().getName(), '结束运行')

t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # 使用默认名字

w.start()
w2.start()
t.start()

调试输出包括每行上当前线程的名称。“线程名称”列中带有“Thread-1”的行对应于未命名的线程w2。

$ python -u threading_names.py

worker Thread-1 开始运行
my_service 开始运行
开始运行
Thread-1worker 结束运行
结束运行
my_service 结束运行

大多数程序不使用打印进行调试。logging支持使用格式化程序代码%(threadName)在每个日志消息中嵌入线程名称。在日志消息中包含线程名称可以更容易地将这些消息追溯到其源。

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
                    )


def worker():
    logging.debug('开始运行')
    time.sleep(2)
    logging.debug('结束运行')


def my_service():
    logging.debug('开始运行')
    time.sleep(3)
    logging.debug('结束运行')


t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker)  # 使用默认名字

w.start()
w2.start()
t.start()

logging是线程安全的,因此来自不同线程的消息在输出中保持不同。

$ python threading_names_log.py

[DEBUG] (worker    ) 开始运行
[DEBUG] (Thread-1  ) 开始运行
[DEBUG] (my_service) 开始运行
[DEBUG] (worker    ) 结束运行
[DEBUG] (Thread-1  ) 结束运行
[DEBUG] (my_service) 结束运行

守护程序与非守护程序线程

到目前为止,示例程序已隐式地等待退出,直到所有线程都完成了它们的工作。有时程序生成一个线程作为守护进程运行,而该线程在运行时不会阻止主程序退出。使用守护进程线程对于那些可能无法轻松中断线程或让线程在其工作过程中死亡不会丢失或损坏数据的服务(例如,为服务监视工具生成“心跳”的线程)非常有用。要将线程标记为守护程序,请使用布尔参数调用其setDaemon()方法。默认情况下,线程不是守护程序,因此传递True将打开守护程序模式。

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )


def daemon():
    logging.debug('开始运行')
    time.sleep(2)
    logging.debug('结束运行')


d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)


def non_daemon():
    logging.debug('开始运行')
    logging.debug('结束运行')


t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

请注意,输出不包括来自守护进程线程的“结束运行”消息,因为所有非守护进程线程(包括主线程)都在守护进程线程从其两秒钟的睡眠中唤醒之前退出。

$ python threading_daemon.py

(daemon    ) 开始运行
(non-daemon) 开始运行
(non-daemon) 结束运行

要等到守护进程线程完成其工作,请使用join()方法。

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('开始运行')
    time.sleep(2)
    logging.debug('结束运行')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('开始运行')
    logging.debug('结束运行')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

d.join()
t.join()

等待守护线程使用join()退出意味着它有机会生成“结束运行”消息。

$ python threading_daemon_join.py

(daemon    ) 开始运行
(non-daemon) 开始运行
(non-daemon) 结束运行
(daemon    ) 结束运行

默认情况下,join()无限期阻塞。也可以传递一个超时参数(一个浮点数,表示等待线程变为非活动状态的秒数)。如果线程没有在超时时间内完成,join()仍然返回。

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('开始运行')
    time.sleep(2)
    logging.debug('结束运行')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('开始运行')
    logging.debug('结束运行')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

d.join(1)
# python2写法
print ('d.isAlive()', d.isAlive())
# python3写法
print ('d.is_alive()', d.is_alive())
t.join()

由于传递的超时值小于守护进程线程的睡眠时间,因此join()返回后,线程仍然是“活动的”。

$ python threading_daemon_join_timeout.py

(daemon    ) 开始运行
(non-daemon) 开始运行
(non-daemon) 结束运行
d.isAlive() True
d.is_alive() True

枚举所有线程

没有必要保留所有守护进程线程的显式句柄,以确保它们在退出主进程之前已完成。enumerate()返回活动线程实例的列表。该列表包含当前线程,并且由于不允许加入当前线程(这会导致死锁情况),因此必须跳过它。

import random
import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def worker():
    """线程worker函数"""
    t = threading.currentThread()
    pause = random.randint(1,5)
    logging.debug('sleeping %s', pause)
    time.sleep(pause)
    logging.debug('ending')
    return

for i in range(3):
    t = threading.Thread(target=worker)
    t.setDaemon(True)
    t.start()

main_thread = threading.currentThread()
for t in threading.enumerate():
    if t is main_thread:
        continue
    logging.debug(f'joining { t.getName()}')
    t.join()

由于worker睡眠的时间是随机的,所以这个程序的输出可能会有所不同。应该是这样的:

$ python threading_enumerate.py

(Thread-1  ) sleeping 3
(Thread-2  ) sleeping 2
(Thread-3  ) sleeping 5
(MainThread) joining Thread-1
(Thread-2  ) ending
(Thread-1  ) ending
(MainThread) joining Thread-3
(Thread-3  ) ending
(MainThread) joining Thread-

子类化线程

在启动时,线程进行一些基本的初始化,然后调用其run()方法,该方法调用传递给构造函数的目标函数。若要创建Thread的子类,请重写run()以执行任何必要的操作。

import threading
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

class MyThread(threading.Thread):

    def run(self):
        logging.debug('running')
        return

for i in range(5):
    t = MyThread()
    t.start()

忽略run()的返回值。

$ python threading_subclass.py

(Thread-1  ) running
(Thread-2  ) running
(Thread-3  ) running
(Thread-4  ) running
(Thread-5  ) running

因为传递给Thread构造函数的args和kwargs值保存在私有变量中,因此不容易从子类访问它们。要将参数传递给自定义线程类型,请重新定义构造函数以将值保存在实例属性中,该属性可以在子类中看到。

import threading
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

class MyThreadWithArgs(threading.Thread):

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name,
                                  verbose=verbose)
        self.args = args
        self.kwargs = kwargs
        return

    def run(self):
        logging.debug('running with %s and %s', self.args, self.kwargs)
        return

for i in range(5):
    t = MyThreadWithArgs(args=(i,), kwargs={'a':'A', 'b':'B'})
    t.start()

MyThreadWithArgs与Thread使用相同的API,但是与其他任何类一样,另一个类可以轻松地更改构造函数方法以采用与线程目的更直接相关的更多或不同的参数。

$ python threading_subclass_args.py

(Thread-1  ) running with (0,) and {'a': 'A', 'b': 'B'}
(Thread-2  ) running with (1,) and {'a': 'A', 'b': 'B'}
(Thread-3  ) running with (2,) and {'a': 'A', 'b': 'B'}
(Thread-4  ) running with (3,) and {'a': 'A', 'b': 'B'}
(Thread-5  ) running with (4,) and {'a': 'A', 'b': 'B'}

计时器线程

Timer提供了一个将Thread子类化的原因的示例,它也包含在线程中。计时器在延迟之后开始工作,并且可以在该延迟时间段内的任何时间取消。

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def delayed():
    logging.debug('worker running')
    return

t1 = threading.Timer(3, delayed)
t1.setName('t1')
t2 = threading.Timer(3, delayed)
t2.setName('t2')

logging.debug('starting timers')
t1.start()
t2.start()

logging.debug('waiting before canceling %s', t2.getName())
time.sleep(2)
logging.debug('canceling %s', t2.getName())
t2.cancel()
logging.debug('done')

请注意,第二个计时器从不运行,而第一个计时器似乎在主程序的其余部分完成后运行。因为它不是守护进程线程,所以当主线程完成时,它是隐式连接的。

$ python threading_timer.py

(MainThread) starting timers
(MainThread) waiting before canceling t2
(MainThread) canceling t2
(MainThread) done
(t1        ) worker running

线程间信令

虽然使用多个线程的目的是分离出单独的操作以并发运行,但有时能够在两个或多个线程中同步这些操作是很重要的。线程之间通信的一个简单方法是使用事件对象。事件管理内部标志,调用者可以set()或clear()。其他线程可以wait()设置set(),有效地阻止进程,直到允许继续。

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )
                    
def wait_for_event(e):
    """Wait for the event to be set before doing anything"""
    logging.debug('wait_for_event starting')
    event_is_set = e.wait()
    logging.debug('event set: %s', event_is_set)

def wait_for_event_timeout(e, t):
    """Wait t seconds and then timeout"""
    while not e.isSet():
        logging.debug('wait_for_event_timeout starting')
        event_is_set = e.wait(t)
        logging.debug('event set: %s', event_is_set)
        if event_is_set:
            logging.debug('processing event')
        else:
            logging.debug('doing other work')


e = threading.Event()
t1 = threading.Thread(name='block', 
                      target=wait_for_event,
                      args=(e,))
t1.start()

t2 = threading.Thread(name='non-block', 
                      target=wait_for_event_timeout, 
                      args=(e, 2))
t2.start()

logging.debug('Waiting before calling Event.set()')
time.sleep(3)
e.set()
logging.debug('Event is set')

wait()方法在等待表示时间的参数之前占用了秒数。它返回一个布尔值,指示是否设置了事件,因此调用者知道wait()返回的原因。isSet()方法可以单独用于事件,而不必担心阻塞。

在本例中,wait_for_event_timeout()检查事件状态,不会无限期阻塞。wait_for_event()会阻塞对wait()的调用,直到事件状态更改后才会返回。

$ python threading_event.py

(block     ) wait_for_event starting
(non-block ) wait_for_event_timeout starting
(MainThread) Waiting before calling Event.set()
(non-block ) event set: False
(non-block ) doing other work
(non-block ) wait_for_event_timeout starting
(MainThread) Event is set
(block     ) event set: True
(non-block ) event set: True
(non-block ) processing event
Python之进程+线程+协程(进程的本质 与 threading线程模块) 文章目录基本概念threading线程模块 本篇开始分析Python中的并发程序,也就是进程、线程、协程序的使用。由于是用自己的语言总结的,因此比较大白话,或者叫通俗易懂。而且很多细节方面没有具体介绍,因为在Python进程管理中很少用到,这里主要分析的就是比较重要的点 基本概念 1、操作系统的本质 帮助我们控制硬件、管理软件的软件,对下提供了一个我们控制计算机的接口,对上帮助我们管理应用软件 2... 阅读详情

相关推荐

Python用一行代码,截取图片

本文是该专栏的第2篇,后面会持续分享python的各种黑科技知识,值得关注。在工作上,有些时候可能需要用到代码来进行自动截图,比如说需要图文识别,进行数据信息抽取的时候,能自动定位截图无疑是很好的办法。对python而言,截图方法其实有很多,但笔者下面要介绍的几种方法,只需要一行代码即可自动截图。废话不多说,直接往下看

Python进阶专栏《爬虫实战进阶》,《Pyppeteer从入门到精通》原创作者 4608

3行python代码实现桌面截图

只需3行代码,就可以给你的电脑桌面截图,保存成jpg图片,首先安装pillow pip install pillow 使用ImageGrab类 from PIL import ImageGrab pic = ImageGrab.grab()pic.save('desktop.jpg') 程序执行时,桌面的内容是什么,截图后的图片内容就是什么,如果你的孩子偷偷玩电脑游戏,而你又抓不到,那么你可以写程序每隔3秒钟截取一张图片,再将这些图片拼接成gif, 就可以查看孩子是否玩游戏了,也算是一种监控手段

Python学习Q群696455390 609

Python与Wind量化接口实战:从配置到数据提取全流程解析

本文详细解析了Python与Wind量化接口的实战应用,从环境配置到数据提取全流程。通过Anaconda管理Python环境,安装WindPy接口,实现历史行情、截面数据和实时行情的查询与优化。文章还提供了高级功能如批量查询、数据缓存策略及实战案例,帮助开发者高效构建量化分析框架。

omega的博客 1342

python BitBlt PrintWindow 对整个桌面进行截图 对后台运行应用界面进行截图

两份代码,自己组合下就能形成花式截图。 # 截图整个桌面 import win32gui import win32ui import win32con import win32api # 获取桌面 hdesktop = win32gui.GetDesktopWindow() # 分辨率适应 width = win32api.GetSystemMetrics(win32con.SM_CXV

心之所向 1万+

跨模型的 API 调用与集成:使用 Spring AI 构建可移植的 API 代码,支持多个 AI 模型(如 OpenAI、Anthropic 等)的调用

Spring AI 是 Spring 生态系统中的一部分,旨在提供一种简单、可扩展的方式来集成人工智能模型。Spring AI 使得开发者可以使用现有的 Spring 体系结构方便地访问多种 AI 模型和服务,例如 OpenAI、Anthropic、HuggingFace 等。

秋元的博客 2414

PCB板质量测试和PCB板

PCB板质量测试和板厂

weixin_51370842的博客 525

Python 三种方法实现截图【详解+完整代码】

其实也大可不必哈哈哈

xff123456_的博客 1万+

【一文读懂】NTN(非地面网络)技术介绍

NTN,即非地面网络,是指利用卫星、高空平台(如无人机、平流层气球等)等非地面通信基础设施来实现全球通信覆盖的网络。在5G时代,NTN主要基于5G标准,特别是5G NR(New Radio)技术,通过卫星通信扩展地面网络的覆盖范围和服务能力。NTN技术的出现和发展,为全球通信带来了新的可能性和挑战。通过不断的技术创新和标准化推进,NTN有望在未来发挥更加重要的作用,为全球用户提供无处不在的通信服务。随着6G时代的到来,我们有理由相信NTN技术将迎来更加广阔的发展前景。

u011376987的博客 1万+

python 三种方式实现截屏(详解+完整代码)

PIL中的ImageGrab模块# 使用PIL中的ImageGrab模块简单,但是效率有点低# PIL是Python Imaging Library,它为python解释器提供图像编辑函数能力。ImageGrab模块可用于将屏幕或剪贴板的内容复制到PIL图像存储器中。# PIL.ImageGrab.grab()方法拍摄屏幕快照。边框内的像素在Windows上以“RGB”图像的形式返回,在macOS上以“RGBA”的形式返回。# 如果省略了边界框,则会复制整个屏幕。...

c_lanxiaofang的博客 4万+

微波无源器件 功分器1 新型方波导双模无功功分器

本名证明了一种基于有着特定功能的(dedicated)T性匹配元件(散射件)的进化结点的新型波导双模两路功分器的可行性。这个散射件,有着面向三个部分的匹配部分,提供了等效功分并且朝着对应的输出端口传输矩形波导的两个TE10/TE01正交模式。所提出的设计紧凑,易于比例变化并且能够级联来获得。

qq_45245770的博客 1401

【SoloPi】SoloPi使用2-功能使用,录制回放

Soloπ是什么 Soloπ是一个无线化、非侵入式的Android自动化工具,公测版拥有录制回放、性能测试、一机多控三项主要功能,能为测试开发人员节省宝贵时间。 录制回放功能 Soloπ拥有录制操作的能力,用户只需要通过Soloπ执行用例步骤,Soloπ就能够将用户的操作记录下来,并且支持在各个设备上进行回放,这一切都能够在手机上独立完成。 ...

q_Catherine的博客 5838

python3 sleep 并发_python基础线程-管理并发线程

线程模块建立在线程的底层特性之上,使线程的工作变得更简单、更像python。使用线程允许程序在同一进程空间中并发运行多个操作。点击此处,获取海量Python学习资料!线程对象使用线程最简单的方法是用目标函数实例化它,然后调用start()让它开始工作。import threading def worker(): """线程worker函数""" print('Worker') ...

weixin_39557419的博客 136

详解AUTOSAR:AUTOSAR架构中的配置文件(拓展篇—7)

查看AUTOSAR代码包时会发现一些这样格式的文件:xxx_PBcfg.c、xxx_Lcfg.c和xxx_Cfg.h,本篇博文讲一讲这几个配置文件的作用和特点。

不脱发的程序猿 2156

python线程wait_python基础线程-管理并发线程

线程模块建立在线程的底层特性之上,使线程的工作变得更简单、更像python。使用线程允许程序在同一进程空间中并发运行多个操作。线程对象使用线程最简单的方法是用目标函数实例化它,然后调用start()让它开始工作。import threadingdef worker():"""线程worker函数"""print('Worker')returnthreads = []for i in range(5...

weixin_39863616的博客 397

Windows密码忘了怎么办?一分钟看懂Windows密码底层机制:无需重装系统也能无痕找回登录密码

忘记Windows开机密码,不一定非得重装系统!本文手把手教你通过提取NTLM Hash值实现“无痕找回密码”,无需PE、无需清除密码,对系统零修改 🛡️ 搭配mimikatz与在线解密平台,小白也能快速上手,了解Windows密码底层机制 🔐

XiaoqiangClub的博客 140

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

python--实验14 并发编程(多线程)

定义通过声明Thread的派生类,创建一个子类,并重写对象的run方法,然后创建其对象实例,可创建线程。通过对象的start方法,可启动线程,并自动执行对象的run方法。注意子类的构造器一定要先调用基类的构造器直接将线程需要做的事写到run方法中示例。

wumingzei的博客 1652

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

027-多线程与并发编程

多线程与并发编程摘要 本章深入探讨Python多线程与并发编程技术,主要内容包括: 并发与并行的核心概念及区别 全局解释器锁(GIL)对多线程的影响 线程同步机制与竞态条件避免 线程池和任务队列的实现 线程间通信与数据共享 性能优化与常见陷阱 通过代码示例演示了顺序执行、并发执行(多线程)和并行执行(多进程)的不同效果,特别分析了GIL对CPU密集型任务和IO密集型任务的影响。

lvjesus的博客 1167

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

并发和并行以及线程安全

并发:指的是任务数>CPU核数,通过操作系统的各种任务调度算法,实现多个任务"一起执行"(实际上总有些任务不在执行,因为CPU切换任务的速度非常快,看上去在一起执行而已).并发针对的是同一段时间内,有多个任务数在运行,强调同一段时间范围. 并行:指的是任务数≤CPU核数,即任务真的在一起执行.并行针对的同一时刻有多个任务数在运行,强调的是同一时刻. 并发与并行在CPU层面的表现: 同步和异步 同步:是指线程在访问某一资源时,获得了资源的返回结果之后才会执行其他操作(强调.....

qq_40132294的博客 3659

Python 如果做到高并发?

3.使用多进程: 因为 Python 的 GIL ( GlobalInterpreter Lock) 限制了单个线程的 CPU 并发能力,如果想要更好的利用 CPU 资源,可以使用多进程, multiprocessing 模块来实现。1.使用标准库 threading:这是 Python 标准库中内置的线程模块,提供了基本的线程管理和同步功能,如创建线程、获取线程状态、实现线程间同步等。具体实现方法可以参考相关文档和代码示例,我们可以根据自己的需求选择合适的方法实现。

Spiderzhaoyi的博客 2195

Python多线程并发启动Appium服务,提升移动UI自动化测试效率

在软件测试领域,自动化测试是提升交付效率和质量保障的关键技术。其核心原理是通过脚本模拟用户操作,替代重复性人工测试,实现快速反馈和持续验证。对于移动端应用,Appium作为主流的跨平台UI自动化测试框架,其价值在于能够使用同一套API测试iOS和Android应用。然而,在实际工程实践中,单设备串行执行测试用例往往成为效率瓶颈,特别是在需要多设备并行验证的回归测试场景中。通过Python的多线程编程,可以自动化、批量地管理多个Appium服务实例,实现测试基础设施的自动化部署与管理。这种方法将测试人员从繁琐

weixin_34238633的博客 407

Python多线程学习及UDP多任务聊天器案例分享

简单地说,就是操作系统可以同时运行多个任务。单核CPU也能执行多任务。多任务优势:在多核或多,或支持Hyper-threading的CPU上使用多线程程序设计的好处是显而易见,即提高了程序的执行吞吐率。在单CPU单核的计算机上,使用,也可以把进程中负责I/O处理、人机交互而常被阻塞的部分与密集计算的部分分开来执行,编写专门的workhorse线程执行密集计算,从而提高了程序的执行效率。python默认单任务执行。

2401_82928104的博客 2102

python线程池模块_python并发编程之进程池,线程池,协程

需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池。其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉只要你用并发,就会有锁的问题,但是你不能一直去自己加锁吧那么我们就用QUEUE,这样还解决了自动加锁的问题由Queue延伸出的一个点也非常重要的概念。以后写程序也会用到这个思想。就是生产者与消费者问题一、Python标准模块--concurrent.fu...

weixin_39742568的博客 299

Python多线程以及判断线程是否结束

python,多线程,结束

weixin_42991437的博客 7040

11.python3标准库--使用进程、线程和协程提供并发性

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ''' python提供了一些复杂的工具用于管理使用进程和线程的并发操作。 通过应用这些计数,使用这些模块并发地运行作业的各个部分,即便是一些相当简单的程序也可以更快的运行 subproces...

weixin_30596343的博客 196

python并发编程(理解多进程,多线程,多任务)

多线程与多进程的基本概念,python中实现多线程与多进程的示例代码。

艽野尘梦的博客 260
上一篇: python3 中文繁体转换简体,简体转换为繁体,汉字转换拼音
下一篇: python 把pdf转成图片文件,防止复制盗用
Python_sn
博客等级 码龄6年 326粉丝 290原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址