时间提醒

import threading
import logging
import timedef thread_function(name):logging.info("Thread %s starting", name)time.sleep(2000)logging.info("Thread %s finishing", name)if __name__ == "__main__":format = "%(asctime)s: %(message)s"logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")logging.info("Main : before creating thread")x = threading.Thread(target=thread_function, args=(1,))logging.info("Main : wait for the thread to finish")logging.info("Main : all done")

daemon

含有daemon标识的线程,当程序结束的时候,线程强制结束

import threading
import logging
import timedef thread_function(name):logging.info("Thread %s starting", name)time.sleep(2)logging.info("Thread %s finishing", name)if __name__ == "__main__":format = "%(asctime)s: %(message)s"logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")logging.info("Main : before creating thread")x = threading.Thread(target=thread_function, args=(1,),  daemon=True)x.start()logging.info("Main : wait for the thread to finish")logging.info("Main : all done")

结束子线程后结束主线程

使用join

import threading
import logging
import timedef thread_function(name):logging.info("Thread %s starting", name)time.sleep(2)logging.info("Thread %s finishing", name)if __name__ == "__main__":format = "%(asctime)s: %(message)s"logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")logging.info("Main : before creating thread")x = threading.Thread(target=thread_function, args=(1,),  daemon=True)x.start()logging.info("Main : wait for the thread to finish")x.join() # 加上这一句会强制等待所有子线程结束后结束主线程logging.info("Main : all done")

启动多线程的方法

ThreadPoolExecutor头文件

import concurrent.futures

实际调用

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:executor.map(thread_function, range(3))

加锁(包含对with 语句的理解)

生产者消费者线程

快的是生产者(要理发的人),慢的是消费者(理发师)
生产者排队,将一个随机信息发给消费者

import logging
import threading
import concurrent.futures
import time
import randomSENTINEL = object()class Pipeline(object):def __init__(self):self.message = 0self.producer_lock = threading.Lock()self.consumer_lock = threading.Lock()self.consumer_lock.acquire()def get_message(self, name):logging.debug("%s: about to acquire getlock", name)self.consumer_lock.acquire()logging.debug("%s: have getlock", name)message = self.messagelogging.debug("%s: about to release setlock", name)self.producer_lock.release()logging.debug("%s: setlock released", name)return messagedef set_message(self, message, name):logging.debug("%s: about to acquire setlock", name)self.producer_lock.acquire()logging.debug("%s: have setlock", name)self.message = messagelogging.debug("%s: about to release getlock", name)self.consumer_lock.release()logging.debug("%s: have released getlock", name)def producer(pipeline):'''pretend we are getting a message from the network'''for index in range(10):message = random.randint(1, 101)logging.info("Producer got message: %s", message)pipeline.set_message(message, "Producer")# send a sentinel message to tell consumer we're donepipeline.set_message(SENTINEL, "Producer")def consumer(pipeline):message = 0while message is not SENTINEL:message = pipeline.get_message("Consumer")if message is not SENTINEL:logging.info("Consumer storing message %s", message)if __name__ == '__main__':format = "%(asctime)s: %(message)s"logging.getLogger().setLevel(logging.DEBUG)logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")pipeline = Pipeline()with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:executor.submit(producer, pipeline)executor.submit(consumer, pipeline)

多进程读写锁

写的时候不能有人读或者写,读的时候没人写就行

import logging
import threading
import concurrent.futures
import time
import randomSENTINEL = object()class Pipeline(object):def __init__(self):self.message = 0self.producer_lock = threading.Lock()self.consumer_lock = threading.Lock()def get_message(self, name):while True:if not self.producer_lock.locked():logging.debug("%s: no write, begin to read", name)self.consumer_lock.acquire()logging.debug("%s: have get readlock", name)message = self.messagelogging.debug("%s: have get the message, about to release readlock", name)self.consumer_lock.release()breakreturn messagedef set_message(self, message, name):while True:if not self.consumer_lock.locked() and not self.producer_lock.locked():logging.debug("%s: no write and read, begin to write", name)self.producer_lock.acquire()logging.debug("%s: get setlock", name)self.message = messagelogging.debug("%s: setover about to release setlock", name)self.producer_lock.release()breakreturndef producer(pipeline):'''pretend we are getting a message from the network'''for index in range(10):message = random.randint(1, 101)logging.info("Producer got message: %s", message)pipeline.set_message(message, "Producer")# send a sentinel message to tell consumer we're donepipeline.set_message(SENTINEL, "Producer")def consumer(pipeline):message = 0while message is not SENTINEL:message = pipeline.get_message("Consumer")if message is not SENTINEL:logging.info("Consumer storing message %s", message)if __name__ == '__main__':format = "%(asctime)s: %(message)s"logging.getLogger().setLevel(logging.DEBUG)logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")pipeline = Pipeline()with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:executor.submit(producer, pipeline)executor.submit(producer, pipeline)executor.submit(consumer, pipeline)

python多线程信息提示相关推荐

  1. 基于python多线程和Scrapy爬取链家网房价成交信息

    文章目录 知识背景 Scrapy- spider 爬虫框架 SQLite数据库 python多线程 爬取流程详解 爬取房价信息 封装数据库类,方便多线程操作 数据库插入操作 构建爬虫爬取数据 基于百度 ...

  2. python多线程爬虫实例-Python实现多线程爬虫

    编辑推荐: 本文主要介绍对Python多线程爬虫实战的整体的思路,希望对大家有帮助. 本文来知乎,由火龙果软件Alice编辑,推荐. 最近在写爬虫程序爬取亚马逊上的评论信息,因此也自学了很多爬虫相关的 ...

  3. 使用Python多线程犯的错误总结

    在使用Python多线程的时候,在使用多线程编程的时候,由于对于变量作用域和多线程不是很熟悉,导致在使用多线程的时候,犯了低级的错误. 第一个错误: 在多线程中使用全局变量,导致多个线程修改全局变量. ...

  4. python多线程实现访问页面_Python实现多线程爬虫

    最近在写爬虫程序爬取亚马逊上的评论信息,因此也自学了很多爬虫相关的知识,其实网络上已经有很多基于Python的入门爬虫程序了,所以学习起来比较方便,唯独那个多线程爬虫一直都学的不是很明白,所以就写下这 ...

  5. python 多线程和协程结合_一文讲透 “进程、线程、协程”

    本文从操作系统原理出发结合代码实践讲解了以下内容: 什么是进程,线程和协程? 它们之间的关系是什么? 为什么说Python中的多线程是伪多线程? 不同的应用场景该如何选择技术方案? ... 什么是进程 ...

  6. python 多线程及线程间通信

    python 多线程 import threading import time def run(n):print("task", n)time.sleep(1)print('2s' ...

  7. python多线程和多进程的使用_python多线程与多进程

    python多线程与多进程 python多线程 python中提供两个标准库thread和threading用于对线程的支持,python3中已放弃对前者的支持,后者是一种更高层次封装的线程库,接下来 ...

  8. 人生苦短之Python多线程

    #encoding=utf-8 import threading import time''' python多线程并不是真正意义上的多线程,通常我们所说的多线程是多个线程同时执行某功能,而在pytho ...

  9. python多线程输出_Python多线程

    多线程基础概念 并行与并发 并行:同时处理多个任务,必须在多核环境下 一段时间内同时处理多个任务,单核也可以并发 并发手段 线程:内核空间的调度 进程:内核空间的调度 协程:用户空间的调度 线程可以允 ...

最新文章

  1. 不吹牛,中国车主已经实现了「停车自由」
  2. MultiByteToWideChar和WideCharToMultiByte用法详解
  3. 使用PHPExcel判别和格式化Excel中的日期格式
  4. [CCF] 201612-2 工资计算
  5. java事件监听器无效_Java的事件监听器学习心得
  6. nunit 2.2.3 released, 支持vs2005 和.net 2.0了.
  7. 微软发布PowerShell Core第一个版本:支持多平台开发
  8. 阿里在使用一种更灵活的软件集成发布模式
  9. 怎么自己发表计算机学术论文,计算机学术论文写做与发表
  10. 基于java实现学科竞赛管理系统「Springboot+mybatis+lyaui」
  11. 关于彻底删除捆绑软件的解决方案
  12. java while循环 计算机,Java while和do ... while循环 - 芒果文档
  13. 联想小新一键恢复小孔_联想小新笔记本怎么一键恢复|联想小新air恢复出厂系统步骤...
  14. 爬虫练习三:爬取链家二手房信息
  15. DIY人体红外报警器手机接收通知 防贼防盗防老王 物联网 智能家居
  16. 找不到Vivado卸载程序的解决方案
  17. 使用新版FLIR (FLIR_ADAS_v2) 训练Faster RCNN模型
  18. Python(1)自动发送邮件
  19. 奋斗(2)第15集剧情介绍
  20. cocos2d-x 学习笔记(1)关于cocos2d-x(环境配置,项目结构,文件说明)

热门文章

  1. Python_基础_2
  2. 数据结构与算法(2)——栈和队列
  3. Java 守护线程概述
  4. 分类器评价与在R中的实现:收益图与提升图
  5. 深度学习(二十)基于Overfeat的物体检测-2014 ICLR-未完待续
  6. 边缘检测:Sobel、拉普拉斯算子
  7. 《大话数据结构》样章试读
  8. Stanford UFLDL教程 反向传播算法(BP算法)
  9. AI 芯片让你升级智能手机,IoT计算智能革命爆发
  10. VMWare常用快捷键