线程的概念及Thread模块的使用
线程
一.什么是线程?
我们可以把进程理解成一个资源空间,真正被CPU执行的就是进程里的线程。
一个进程中最少会有一条线程,同一进程下的每个线程之间资源是共享的。

二.开设线程的两种方式
开设进程需要做哪些操作
1.重新申请一块内存空间
2.将所需的资源全部导入
开设线程需要做哪些操作
上述两个步骤都不需要 所以开设线程消耗的资源远比开设进程的少!!!
from threading import Thread # 线程模块
import time
# 正常方法
def test(name):
print(f'{name} is running')
time.sleep(2)
print(f'{name} is over')
t = Thread(target=test, args=('jason',))
t.start()
print('主线程')
# 重写类方法
class Myclass(Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
print(f'{self.name} is running')
time.sleep(3)
print(f'{self.name} is over')
t = Myclass('jason')
t.start()
print('主线程')


线程对象的其他方法
from threading import Thread, active_count, current_thread
def test(name):
print(f'{name} is running')
print(current_thread().name)
time.sleep(2)
print(f'{name} is over')
t = Thread(target=test, args=('jason',))
t.start()
print(current_thread().name)
t.join() # 等待子线程执行完再执行主线程(和进程的join一样)
print('主线程')


三.守护线程
定义
随着守护线程的主线程结束,子线程也会立即关闭, 所以主线程需要等待里面所有非守护线程的结束才能结束
开启方式和上面的守护进程一样,在线程的start开启前,加入线程名.dameo = True 即可开启该线程的守护线程
小练习
下面的代码的打印顺序是如何的:
from threading import Thread
from multiprocessing import Process
import time
def foo():
print(123)
time.sleep(3)
print("end123")
def bar():
print(456)
time.sleep(1)
print("end456")
if __name__ == '__main__':
t1=Thread(target=foo)
t2=Thread(target=bar)
t1.daemon=True
t1.start()
t2.start()
print("main-------")

四.线程数据共享
from threading import Thread
money = 100
def test():
global money
money = 999
t = Thread(target=test)
t.start()
t.join()
print(money)

五.线程互斥锁
和进程互斥锁一样,都是为了解决并发带来的修改同一数据时,数据错乱的情况,虽然减少了效率但是增加了数据的安全性。
加锁
from threading import Thread, Lock
import time
num = 100
def test():
locked.acquire() # 放置锁
global num
# 先获取num的数值
tmp = num
# 模拟延迟效果
time.sleep(0.05)
# 修改数值
tmp -= 1
num = tmp
locked.release() # 解除锁
t_list = []
locked = Lock() # 生成锁
for i in range(100):
t = Thread(target=test)
t.start()
t_list.append(t)
# 确保所有子线程全部结束
for t in t_list:
t.join()
print(num)
线程的概念及Thread模块的使用的更多相关文章
- 进程的概念及multiprocess模块的使用
一.进程 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机结构中,进程是程序的基本执行实体:在 ...
- python全栈开发 * 线程锁 Thread 模块 其他 * 180730
一,线程Thread模块1.效率更高(相对于进程) import time from multiprocessing import Process from threading import Thre ...
- 【Python@Thread】thread模块
一.关于Python多线程 Python解释器中可以同时运行多个线程,但是再任意时刻只能有一个线程在解释器运行. Python虚拟机的访问是由全局解锁器(GIL)控制的,由GIL保证同时只有一个线程的 ...
- Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块
Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fab ...
- python标准库介绍——33 thread 模块详解
?==thread 模块== (可选) ``thread`` 模块提为线程提供了一个低级 (low_level) 的接口, 如 [Example 3-6 #eg-3-6] 所示. 只有你在编译解释器时 ...
- thread模块—Python多线程编程
Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...
- 【转】php Thread Safe(线程安全)和None Thread Safe(NTS,非 线程安全)之分
Windows版的PHP从版本5.2.1开始有Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分,这两者不同在于何处?到底应该用哪种?这里做一个简单的介绍. ...
- Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分
Windows版的PHP从版本5.2.1开始有Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分,这两者不同在于何处?到底应该用哪种?这里做一个简单的介绍. ...
- 【转】java线程系列---Runnable和Thread的区别
在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口:Thread类是在java.lang包中定义的.一个类只要继承了Thread类同时覆写了本类中的run() ...
随机推荐
- Apache HTTPD 未知后缀解析漏洞
环境搭建 https://blog.csdn.net/qq_36374896/article/details/84102101 该环境版本: PHP 7.x 最新版 Apache HTTPD 2.4. ...
- 解决Hadoop集群hdfs无法启动DataNode的问题
问题描述: 在hadoop启动hdfs的之后,使用jps命令查看运行情况时发现hdfs的DataNode并没有打开. 笔者出现此情况前曾使用hdfs namenode -format格式化了hdfs ...
- CF1545X Codeforces Round #732
A. AquaMoon and Strange Sort 叉人题 如果数字各不相同,只需要统计每个数参与构成的逆序对总数,如果是奇数一定最终朝左,偶数朝右.无意义的数字交换对方向是没有影响的 继续考虑 ...
- C/C++ 文件读写
•前言 第一次接触文件读写是在大一的C语言教材中,当时哼哧吧唧的学的贼费劲,虽然最后也学会了,但好像没怎么用过. 在后来,就是在OJ上刷题的时候,编写的代码有时候连样例都不能通过: 这个时候就需要各种 ...
- linux更新源管理
1.备份源 主要防止在更新了新的源之后出现错误情况,备份一下现有的源 sudo cp /etc/apt/sources.list /etc/apt/sources.list.old 2.编辑sourc ...
- Makefile学习(一)
objects = main.o kbd.o command.o display.o \ insert.o search.o files.o utils.o ...
- java-設計模式概述
什麽是設計模式?? 软件设计中常见问题的典型解决方案. 能根据需求进行调整的预制蓝图, 可用于解决代码中反复出现的设计问题. 模式并不是一段特定的代码, 而是解决特定问题的一般性概念. 你可以根据模式 ...
- SpringBoot使用JdbcTemplate批量保存
@Autowired DataSourceProperties dataSourceProperties; @Autowired ApplicationContext applicationConte ...
- 学习Puppet(二)
puppet的工作流程 1.简介 puppet是一种采用C/S星状结构的linux.Unix平台的集中配置管理系统.puppet拥有自己的语言,可管理配置文件.用户.cron任务.软件包.系统服务等. ...
- centos安装服务参考博客,亲测可用
centos 安装nginx参考 日志log报错 nginx -c /etc/nginx/nginx.conf https://blog.csdn.net/weixin_41004350/articl ...