python3线程启动与停止
转自:
https://blog.csdn.net/weixin_38125866/article/details/76795462
https://www.cnblogs.com/lcchuguo/p/4687348.html
Python GIL(Global Interpreter Lock)
GIL并不是Python的特性,它是在实现Python解析器(CPython)时所引入的一个概念。就好比C++是一套语言(语法)标准,但是可以用不同的编译器来编译成可执行代码。
有名的编译器例如GCC,INTEL C++,Visual C++等。Python也一样,同样一段代码可以通过CPython,PyPy,Psyco等不同的Python执行环境来执行。
像其中的JPython就没有GIL。然而因为CPython是大部分环境下默认的Python执行环境。所以在很多人的概念里CPython就是Python,也就想当然的把GIL归结为Python语言的缺陷。
所以这里要先明确一点:GIL并不是Python的特性,Python完全可以不依赖于GIL
python3的线程启动支持两种方式:
一种是以传入函数名开启;
另一种是通过重写run方法开启;
以传入函数名开启:
import time
import threading def demo(n):
while n >= 0:
print("n:", n)
n -= 1
time.sleep(1) if __name__=='__main__': t = threading.Thread(target=demo, args=(10,))
t.start()
t.join()
print("exit")
重写run方法:
import time
import threading class A(threading.Thread):
def __init__(self, args):
threading.Thread.__init__(self)
self.args = args def run(self):
n = self.args
while n > 0:
print("n:", n)
n -= 1
time.sleep(1) if __name__=='__main__': t = A(10)
t.start()
t.join()
print("exit")
创建后台线程:
t = threading.Thread(target=demo, args=(20,), daemon=True)
t.start() ------------------------------------------------------------
创建后台线程:
def f0():
pass def f1(a1,a2):
time.sleep(5)
f0() '''下面代码是直接运行下去的,不会等待函数里面设定的sleep'''
t= threading.Thread(target=f1,args=(111,112))#创建线程
t.setDaemon(True)#设置为后台线程,这里默认是False,设置为True之后则主线程不用等待子线程
t.start()#开启线程
import time
import threading def run(n):
print('[%s]------running----\n' % n)
time.sleep(2)
print('--done--') def thread1():
print('starting thread: %s' % threading.current_thread().getName())
for i in range(5):
t = threading.Thread(target=run, args=[i, ])
t.start()
t.join(1) print("start thread %s" % threading.current_thread().getName())
m = threading.Thread(target=thread1, args=(), name="thread1")
m.setDaemon(True) # thread1,它做为程序主线程的守护线程,当主线程退出时,thread1线程也会退出,由thread1启动的其它子线程会同时退出,不管是否执行完任务
m.start()
m.join(timeout=2)
print("---main thread done----")#主线程退出
Note:Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly.
If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as anEvent.
import time
import threading class DownThread:
def __init__(self):
self._running = True def terminate(self):
self._running = False def run(self, n):
while self._running and n > 0:
print('T-minus', n)
n -= 1
time.sleep(1) if __name__=='__main__': c = DownThread()
t = threading.Thread(target=c.run, args=(10,))
t.start()
time.sleep(3)
c.terminate()
t.join()
Python多线程里面的event方法实现线程间通信
Python 通过threading.Event()产生一个event对象。Event默认内置了一个标志,初始值为False,通过set()将其置为True。wait(timeout)则用于堵塞线程直至Flag被set(或者超时,可选的),isSet()用于查询标志位是否为True,
Clear()则用于清除标志位(使之为False)。
当Event对象的内部信号标志为False时。wait方法一直堵塞线程等待到其为真或者超时(若提供,浮点数,单位为秒)才返回,若Event对象内部标志为True则wait()方法马上返回。
def do(event):
print('start')
event.wait()
print('end') if __name__ == "__main__":
event_obj = threading.Event() # 创建一个事件
event_obj.clear() t1 = threading.Thread(target=do, args=(event_obj,))
t1.start() data = input('请输入要:')
if data == 'True':
event_obj.set() # 变绿灯 time.sleep(5)
python3线程启动与停止的更多相关文章
- python3线程介绍01(如何启动和调用线程)
#!/usr/bin/env python# -*- coding:utf-8 -*- import osimport time,randomimport threading # 1-进程说明# 进程 ...
- Java线程的启动和停止(一)
如何构造线程 在运行线程之前需要先构造线程对象,线程对象的构造需要指定线程所需要的属性,比如:所属线程组.线程优先级.是否为Daemon线程等信息.下面我们看一下,java.lang.Thread中对 ...
- 【Java 语言】Java 多线程 一 ( 线程启动 | 线程中断 )
一. 线程启动 线程启动 : -- 1. 继承 Thread 运行线程 : 重写 Thread 类的 run 方法, 然后执行该线程; -- 2. 实现 Runnable 接口, 并运行线程; -- ...
- 【Canal源码分析】Canal Instance启动和停止
一.序列图 1.1 启动 1.2 停止 二.源码分析 2.1 启动 这部分代码其实在ServerRunningMonitor的start()方法中.针对不同的destination,启动不同的Cana ...
- nginx 的安装、启动、停止与重启
一.nginx 基本介绍 1.Nginx 是单进程单线程模型,也就是启动的工作进程只有一个线程响应客户端请求,而 apache 可以在一个进程内启动多个线程响应客户端请求.所以 nginx 的内存占用 ...
- 深入浅出Tomcat/2 - Tomcat启动和停止
Tomcat启动和停止 很明显,我们启动或停止Tomcat,一般调用的是bin下的startup.sh或shutdown.sh(以Linux为例,以下涉及到平台,若无特殊说明,一般都指Linux).我 ...
- c# 线程启动while(true) 死循环,里边的return导致线程退出情况,查错
写了一个线程 线程下启动了一个循环 while(true) { 里边有个判断 如果为空不操作, 有余这个线程是后加的,老程序里边因为有个return没关注,导致线程退出而不能不听的监控 } 线程启动一 ...
- Mongodb 笔记01 MongoDB 简介、MongoDB基础知识、启动和停止MongoDB
MongoDB 简介 1. 易于使用:没有固定的模式,根据需要添加和删除字段更加容易 2. 易于扩展:MongoDB的设计采用横向扩展.面向文档的数据模型使它能很容易的再多台服务器之间进行分割.自动处 ...
- Tomcat源码分析——启动与停止服务
前言 熟悉Tomcat的工程师们,肯定都知道Tomcat是如何启动与停止的.对于startup.sh.startup.bat.shutdown.sh.shutdown.bat等脚本或者批处理命令,大家 ...
随机推荐
- ubuntu 安装pip3 遇到Ignoring ensurepip failure: pip 8.1.1 requires SSL/TLS错误
3.5版本之后的会自动安装pip,所以我们直接从官网下载3.5.2,下载地址:https://www.python.org/ftp/python/ 下载以后,可以用命令解压,也可以右键进行解压, ta ...
- <script src="../build/browser.min.js"></script> 是用来里面babel工具把ES6的语法转成ES5
<!DOCTYPE html> <html> <head> <script src="../build/react.js">< ...
- LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...
- 虚拟机中不能连接usb设备解决办法
虚拟机中不能连接usb设备解决办法 1.点击开始->运行,在对话框中输入"services.msc",确定,打开windows服务管理器.2.在服务列表中选中"VM ...
- JavaScript 第二章总结
Writing real code 设计程序的步骤 First, a high-level design and a flowchart more details Working through th ...
- every day a practice —— morning(2)
Two years at sea have fostered a close relationship between the two fellow sailors as they cross the ...
- uva11609
以三个人组队为例,3组合是:C(3,0)=1,3,3,1.还有队长的选择.有 1*0,3*1,3*2,1*3种. 组合数: 1 3 3 1 ...
- 基于windows使用fabric将gitlab的文件远程同步到服务器(本地)
# -*- coding: utf-8 -*- from fabric.api import env, run, local, put from fabric.operations import su ...
- navicat和 plsql 连接oracle数据库 总结
打开 navicat -->工具-->选项-->oci 右侧选择oci.dll 的路径 默认 在 navicat的安装目录下有一个 instantclient 的文件夹 直接选 ...
- DPDK 16.04/16.11.2 默认tx offload是关闭的引起tx vlan offload无效
打开IXGBE调试日志发发现:tx使用ixgbe_xmit_pkts_vec,默认tx offload无效了PMD: ixgbe_set_tx_function(): Using simple tx ...