线程

一.什么是线程?

我们可以把进程理解成一个资源空间,真正被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模块的使用的更多相关文章

  1. 进程的概念及multiprocess模块的使用

    一.进程 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机结构中,进程是程序的基本执行实体:在 ...

  2. python全栈开发 * 线程锁 Thread 模块 其他 * 180730

    一,线程Thread模块1.效率更高(相对于进程) import time from multiprocessing import Process from threading import Thre ...

  3. 【Python@Thread】thread模块

    一.关于Python多线程 Python解释器中可以同时运行多个线程,但是再任意时刻只能有一个线程在解释器运行. Python虚拟机的访问是由全局解锁器(GIL)控制的,由GIL保证同时只有一个线程的 ...

  4. Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

    Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fab ...

  5. python标准库介绍——33 thread 模块详解

    ?==thread 模块== (可选) ``thread`` 模块提为线程提供了一个低级 (low_level) 的接口, 如 [Example 3-6 #eg-3-6] 所示. 只有你在编译解释器时 ...

  6. thread模块—Python多线程编程

    Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...

  7. 【转】php Thread Safe(线程安全)和None Thread Safe(NTS,非 线程安全)之分

    Windows版的PHP从版本5.2.1开始有Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分,这两者不同在于何处?到底应该用哪种?这里做一个简单的介绍. ...

  8. Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分

    Windows版的PHP从版本5.2.1开始有Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分,这两者不同在于何处?到底应该用哪种?这里做一个简单的介绍. ...

  9. 【转】java线程系列---Runnable和Thread的区别

    在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口:Thread类是在java.lang包中定义的.一个类只要继承了Thread类同时覆写了本类中的run() ...

随机推荐

  1. 爬虫中网络请求的那些事之urllib库

    目录 爬虫之网络请求中的那些事 urllib库 urlopen函数 urlretrieve函数 urlencode.parse_qs函数 urlparse.urlsplit函数: request.Re ...

  2. Redhat7 安装 yum源(亲测有效)

    由于之前安装Redhat7 想安装vsftpd  使用yum   install vsftpd 报错: This system is not registered to Red Hat Subscri ...

  3. MSF基本使用

    MSF 链接数据库 linux查找文件 find / -name dabase.yml 链接数据库 db_connect -y path/database.yml db_status 查询数据库链接状 ...

  4. [转载]SQL注入绕过WAF的方法总结

    基本/简单绕过方法: 1.注释符 http://www.0dayhack.com/index.php?page_id=-15 /*!UNION*/ /*!SELECT*/ 1,2,3,4-. 2.使用 ...

  5. Java的浅克隆和深克隆

    如何实现对象的克隆 (1)实现 Cloneable 接口并重写 Object 类中的 clone() 方法: (2)实现 Serializable 接口,通过对象的序列化和反序列化实现克隆,可以实现真 ...

  6. WindowsServer域用户批量创建方法

    @font-face { font-family: "Times New Roman" } @font-face { font-family: "宋体" } @ ...

  7. JavaScript 的诞生历史

    看到一篇介绍JS诞生历史的文章,很有意思,文章里描述了很多的历史细节 https://webdevelopmenthistory.com/1995-the-birth-of-javascript/

  8. SpringBoot中的日志使用:

    SpringBoot中的日志使用(一) 一:日志简介: 常用的日志接口 commons-logging/slf4j 日志框架:log4j/logback/log4j2 日志接口屏蔽了日志框架的底层实现 ...

  9. zookeeper 负载均衡和 nginx 负载均衡区别 ?

    zk 的负载均衡是可以调控,nginx 只是能调权重,其他需要可控的都需要自己写插件:但是 nginx 的吞吐量比 zk 大很多,应该说按业务选择用哪种方式.

  10. SynchronizedMap 和 ConcurrentHashMap 有什么区别?

    SynchronizedMap 一次锁住整张表来保证线程安全,所以每次只能有一个线程来 访为 map. ConcurrentHashMap 使用分段锁来保证在多线程下的性能. ConcurrentHa ...