多线程(threading)示例
一、多线程简单示例
import threading,time print('第一线程(默认):程序开始啦!') def takeANap():time.sleep(5)print('第二线程:5秒到,我醒来啦!')#创建并启动多线程 t=threading.Thread(target=takeANap) t.start()print('第一线程(默认):程序结束啦!')''' 输出: 第一线程(默认):程序开始啦! 第一线程(默认):程序结束啦! >>> 第二线程:5秒到,我醒来啦! '''
二、多线程传递多参数、可选参数示例
import threading##多线程传递多参数print('Cats','Dogs','Frogs',sep='&')=>Cats & Dogs & Frogs: threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '}) threadObj.start()##输出:Cats & Dogs & Frogs
三、并发问题
可以轻松地创建多个新线程,让它们同时运行。但多线程也可能会导致所谓的并发问题。如果这些线程同时读写变量,导致互相干扰,就会发生并发问题。并发问题可能很难一致地重现,所以难以调试。多线程编程本身就是一个广泛的主题。必须记住的是:为了避免并发问题,绝不让多个线程读取或写入相同的变量。当创建一个新的Thread 对象时,要确保其目标函数只使用该函数中的局部变量。这将避免程序中难以调试的并发问题。
多线程实战,多线程下载漫画:
#! python3 # multidownloadXkcd.py - Downloads XKCD comics using multiple threads.import requests, os, bs4, threading os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcddef downloadXkcd(startComic, endComic):for urlNumber in range(startComic, endComic):# Download the page.print('Downloading page http://xkcd.com/%s...' % (urlNumber))res = requests.get('http://xkcd.com/%s' % (urlNumber))res.raise_for_status()soup = bs4.BeautifulSoup(res.text)# Find the URL of the comic image.comicElem = soup.select('#comic img')if comicElem == []:print('Could not find comic image.')else:comicUrl = comicElem[0].get('src')# Download the image.print('Downloading image %s...' % (comicUrl))res = requests.get(comicUrl)res.raise_for_status()# Save the image to ./xkcdimageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')for chunk in res.iter_content(100000):imageFile.write(chunk)imageFile.close()# Create and start the Thread objects. downloadThreads = [] # a list of all the Thread objects for i in range(0, 1400, 100): # loops 14 times, creates 14 threadsdownloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))downloadThreads.append(downloadThread)downloadThread.start()# Wait for all threads to end. for downloadThread in downloadThreads:downloadThread.join() print('Done.')
转载于:https://www.cnblogs.com/chenxi188/p/10584087.html
多线程(threading)示例相关推荐
- PySide2多线程问题示例:创建新线程、子线程发射信号到主界面
PySide2多线程问题示例:创建新线程.子线程发射信号到主界面 本文是在pyside学习过程中的记录,从无子线程.子线程在主程序中直接操作Qt界面.子线程发射信号操作主界面三个步骤出发,记录对多线程 ...
- javascript worker 多线程 简单示例
javascript worker 多线程 简单示例 项目结构 主线程 index.html <!DOCTYPE html> <html lang="en"> ...
- python的多线程threading
多线程threading 1.Thread创建线程: 上代码: #!/usr/bin/env python3import threading import timedef A():t_name = t ...
- Win32 API 多线程编程示例 - 窗口版
网上有一些Win32 多线程编程示例,多是控制台版本:下面哥作一个窗口版本: /*-------------------------------------------------bobo, 2020 ...
- Python多线程threading和多进程multiprocessing的区别及代码实现
1. 多线程threading import time from threading import Threaddef thread_read(data):while True:print('read ...
- python 多线程 模块_Python多线程threading和multiprocessing模块实例解析
本文研究的主要是Python多线程threading和multiprocessing模块的相关内容,具体介绍如下. 线程是一个进程的实体,是由表示程序运行状态的寄存器(如程序计数器.栈指针)以及堆栈组 ...
- python多线程threading之阻塞线程(join)线程同步和守护线程(setDaemon(True))实例详解
一.多线程(主线程和子线程同时执行) 1.主线程是程序本身,看不到的,主线程和子线程没有依赖关系,同步执行的,若主线程先执行完,会等子线程执行完毕,程序结束 2.启动一个线程就是把一个函数传入并创建T ...
- 多线程-threading和进程VS线程(python 版)
多线程-threading python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用 1. 使用threading模块 ...
- python爬虫之多线程threading、多进程multiprocessing、协程aiohttp 批量下载图片
一.单线程常规下载 常规单线程执行脚本爬取壁纸图片,只爬取一页的图片. import datetime import re import requests from bs4 import Beauti ...
- python并发编程:协程asyncio、多线程threading、多进程multiprocessing
python并发编程:协程.多线程.多进程 CPU密集型计算与IO密集型计算 多线程.多进程与协程的对比 多线程 创建多线程的方法 多线程实现的生产者-消费者爬虫 Lock解决线程安全问题 使用线程池 ...
最新文章
- Java 过一下基础
- Android之底部菜单TabHost的实现
- 如何做好一条0~2岁的产品狗
- web.xml中相关标签的加载顺序
- Windows与Linux区别1
- 电脑计算器_哪几种计算器可以携带入考场!注会考试忘带计算器了怎么办?
- excel打开空白不显示内容 没有隐藏_这些Excel快捷键你都会吗?
- LINQ 学习路程 -- 查询操作 ElementAt, ElementAtOrDefault
- OpenStack混合云的集成问题如何克服?
- 2021考研数学一123分经验分享
- php 时间日期转为时间戳,PHP日期格式转时间戳
- MAC-终端命令大全
- 金山云服务器e1型,金山云-文档中心-重装系统
- 北邮大一第二学期计算机学院课表,北京邮电大学
- centos7设置基础软件仓库时出错
- Matlab plot画图 坐标字体、字号、范围、间隔等的设置
- GKB字符集转UTF-8
- Python进阶之路 简单的棋盘游戏
- npm和package是什么
- 新华社中移动共建搜索引擎