-
2021-04-23 14:45:47
我们通常使用的threading.currentThread().ident,获取的是threading对象的标识ident,而并非系统线程ID。
那么怎么才能获取系统线程ID呢?
答案:
使用ctypes调用系统的动态链接库libc.so.6 来获取线程id。
参考:http://blog.devork.be/2010/09/finding-linux-thread-id-from-within.html
python代码示例:
import ctypes SYS_gettid = 186 libc = ctypes.cdll.LoadLibrary('libc.so.6') tid = libc.syscall(SYS_gettid)
更多相关内容 -
python3 获取 进程id 线程id
2020-11-24 08:30:401.获取线程idimport threading# 1 获取线程ID,NAMEt = threading.currentThread()#线程IDprint('Thread id : %d' % t.ident)#线程NAMEprint('Thread name : %s' % t.getName())输出:Thread id : 7080Thread name : ...1.获取线程id
import threading
# 1 获取线程ID,NAME
t = threading.currentThread()
#线程ID
print('Thread id : %d' % t.ident)
#线程NAME
print('Thread name : %s' % t.getName())
输出:
Thread id : 7080
Thread name : MainThread
2.获取进程id
import psutil
import os
import datetime
pid = os.getpid()
p = psutil.Process(pid)
print('----------------')
#进程ID
print('Process id : %d' % pid)
#进程NAME
print('Process name : %s' % p.name())
#获取进程bin路径
print('Process bin path : %s' % p.exe())
#获取pid对应的路径
print('Process path : %s' % p.cwd())
#进程状态
print('Process status : %s' % p.status())
#进程运行时间
print('Process creation time : %s' % datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S"))
#CPU使用情况
print(p.cpu_times())
#内存使用情况
print('Memory usage : %s%%' % p.memory_percent())
#硬盘读取信息
print(p.io_counters())
#打开进程socket的namedutples列表
print(p.connections())
#此进程的线程数
print('Process number of threads : %s' % p.num_threads())
输出:
Process id : 3136
Process name : python.exe
Process bin path : D:\Programs\Anaconda\python.exe
Process path : D:\1_practice\python\projects\python_accumulate\function\6_并发\线程
Process status : running
Process creation time : 2018-09-04 19:45:39
pcputimes(user=0.062400399999999995, system=0.1092007)
Memory usage : 0.0903536933504%
pio(read_count=507L, write_count=28L, read_bytes=793919L, write_bytes=399L)
[]
Process number of threads : 2
whatday
发布了57 篇原创文章 · 获赞 538 · 访问量 486万+
他的留言板
关注
标签:name,Process,进程,线程,print,id,python3
来源: https://blog.csdn.net/whatday/article/details/104058847
-
linux查看线程执行状态+python获取线程id
2018-12-19 18:23:03ubuntu(linux)跟踪指定进程的线程执行状态的方法 新建一个用于测试的py文件,内容如下 # coding: utf-8 import threading import time import os import ctypes def func(arg): while True: time....ubuntu(linux)跟踪指定进程的线程执行状态的方法
新建一个用于测试的py文件,内容如下# coding: utf-8 import threading import time import os import ctypes def func(arg): while True: time.sleep(1) print('thread:{}, arg={}, pid={}, ppid={}'.format(threading.get_ident(), arg,os.getpid(), ctypes.CDLL('libc.so.6').syscall(186))) return 0 if __name__ == '__main__': threading.Thread(target=func, name='eat', args=(1,),daemon=True).start() threading.Thread(target=func, name='run', args=(2,),daemon=True).start() while True: time.sleep(1)
1、首先使用ps -aux | grep “PROGRAM_WORD”命令去过滤你要查看的进程
获取进程id,如下图:
2、使用 ps -T -p 27850
3、使用 strace -p 27851
注意:如果在docker中无法执行strace命令,则启动docker时增加–priveleged参数即可,例如:docker exec --priveleged -it CONTAINER_NAME bash
另外,本文提供了使用python获取线程id的方法,使用ctypes加载C标准库,然后再通过系统调用获取线程id。
-
python多线程——获取子线程中的值
2020-12-06 12:53:571、定义自己的函数2、加入线程3、启动线程4、等待线程结束看下面的代码from threading import Threadimporttime#定义一个函数,等待5秒后输出datadeffun():data = "123"time.sleep(5)print(data)...点击上方蓝色文字一键关注
点击上方“python学习专栏”,选择“置顶公众号”
干货、福利第一时间送达!
如何开启多线程?
1、定义自己的函数
2、加入线程
3、启动线程
4、等待线程结束
看下面的代码
from threading import Threadimport time# 定义一个函数,等待5秒后输出datadef fun():data = "123"time.sleep(5)print(data)return dataif __name__ == "__main__":#定义一个线程,target为需要执行的目标函数T = Thread(target=fun)# 启动子线程T.start()print("结束")# 输出结果为# 结束# 123
假设这里不加入多线程,而是直接调用,那么输出应该是
123
结束
分析一下过程,if _name__ == "__main__" 相当于一个主线程,而 T 是我们定义的一个子线程,T.start(),开启子线程。
由于这里没有规定,让主线程等待子线程结束,因此会提前输出 结束
开启主线程等待
from threading import Threadimport time# 定义一个函数,等待5秒后输出datadef fun():data = "123"time.sleep(5)print(data)return dataif __name__ == "__main__":#定义一个线程,target为需要执行的目标函数T = Thread(target=fun)# 启动子线程T.start()# 主线程需要等待子线程结束T.join()print("结束")# 输出结果为# 123# 结束
这里只是简单的讲一下线程的操作
如何获取线程中产生的值
首先需要说一下,在线程中,使用return 返回值是不能实现的,你不能拿到这个值,无论你是否开启线程等待。可以自行尝试一下
想要实现这个功能,有两个方法,
1、重写
Thread
重写 Thread,在内部定义一个获取值的函数
import threadingclass MyThread(threading.Thread):"""重写多线程,使其能够返回值"""def __init__(self, target=None, args=()):super(MyThread, self).__init__()self.func = targetself.args = argsdef run(self):self.result = self.func(*self.args)#该函数用于获取返回值,需要开启joindef get_result(self):try:return self.resultexcept Exception:return None
使用自定义的类来实现
from threading import Threadimport time# 定义一个函数,等待5秒后返回datadef fun():data = "123"time.sleep(5)return dataif __name__ == "__main__":#定义一个线程,target为需要执行的目标函数T = MyThread(target=fun)# 启动子线程T.start()# 主线程需要等待子线程结束T.join()# 获取值必须放在 join后面,print(T.get_result())print("结束")# 输出结果为# 123# 结束
join是让主线程等待子线程结束,如果将获取结果放到了主线程join前,此时程序为运行结束,返回值为空
2、使用队列实现
首先定义一个全局队列,将多线程产生的值放到队列中,然后再主线程中获取。
from threading import Threadfrom queue import Queueimport time# 定义一个全局队列,先进先出队列queue_data = Queue()# 定义一个函数,等待5秒后输出datadef fun():data = "123"time.sleep(5)# 将数据压入队列queue_data.put(data)if __name__ == "__main__":#定义一个线程,target为需要执行的目标函数T = Thread(target=fun)# 启动子线程T.start()w = T.join()print(queue_data.get())print("结束")# 输出结果为# 123# 结束
借助concurrent模块,加入线程池中来实现
通过线程池的自带函数获取结果
from threading import Threadfrom queue import Queuefrom concurrent.futures import ThreadPoolExecutorimport time# 定义一个全局队列,先进先出队列queue_data = Queue()pool = ThreadPoolExecutor()# 定义一个函数,等待5秒后输出datadef fun():data = "123"time.sleep(5)# 将数据压入队列queue_data.put(data)return dataif __name__ == "__main__":#定义一个线程,target为需要执行的目标函数t = pool.submit(fun)print(t.result())print("结束")# 输出结果为# 123# 结束
判断线程是否结束
from threading import Threadfrom queue import Queuefrom concurrent.futures import ThreadPoolExecutorimport time# 定义一个全局队列,先进先出队列queue_data = Queue()pool = ThreadPoolExecutor()# 定义一个函数,等待5秒后输出datadef fun():data = "123"time.sleep(5)# 将数据压入队列queue_data.put(data)return dataif __name__ == "__main__":#定义一个线程,target为需要执行的目标函数t = pool.submit(fun)# 判断线程是否结束print(t.done())print("结束")# 输出结果为# False# 结束
通过判断线程是否结束,采用while循环最终获取结果
点赞+关注
END
扫描识别二维码
带你领略不一样的python
-
python 中获取线程id
2018-07-02 16:00:501、python下使用ctypes获取threading线程idpython的多线程坑坑不断… …python的threading因为封装的太好, 很多本源的东西在threading对象里是拿不到的. 首先需要说明的是python threading的name跟ident,这些看起来... -
python线程的ID和Name
2020-12-01 00:39:56多线程环境下用来区分不同线程的ID和Name。线程name在创建的时候可由用户设定。import threadingdef _show_id_name():print(threading.current_thread().name)print(threading.current_thread().ident)print... -
在Python2.6中获取线程ID或名称
2020-11-24 08:30:40我试图在Python2.6中获取线程ID或名称我遵循示例,但是我得到了错误喜欢未定义全局名称“currentThread”未定义全局名称“当前线程”(我尝试了currentThread和current_thread)这是我的代码:vim f3Q.py1 import ... -
python中根据id关闭线程?
2020-12-01 00:40:40import osimport platformimport subprocessimport signalimport timeclass TimeoutError(Exception):passdef command(cmd, timeout=60):"""Run command and return the outputcmd - the command to runtimeout - ma... -
python获取当前线程_如何在Python中找到线程ID
2020-11-24 08:30:40I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of wh... -
python – 正确使用QThread.currentThreadId()
2020-12-05 17:12:29我认为确定当前运行函数的QThread的ID是QThread....线程ID以我无法解释的方式变化,表明我实际上无法使用它,QThread实例id可预测地变化,表明我应该使用它来识别当前正在运行的线程.为了测试,我创建了这个:from... -
python 线程
2018-06-26 08:38:58先说一下 进程 和线程的基本概念 本人理解哈:一个程序就是一个进程 一个进程可以包含多个线程 线程就是进程内部单独执行的程序块我用的是 Python2.7 引用thread python3.X 可以研究一下 threading 但是我写代码... -
python 获取当前运行线程名称和数量 threading.enumerate()
2022-07-21 14:39:14python获取当前运行线程名称和数量threading.enumerate() -
python3 获取 进程id 线程id.pdf
2021-09-14 13:28:56python3 获取 进程id 线程id.pdf -
python threading 线程状态
2021-09-08 17:24:14import threading from time import sleep def demo_func_one(): sleep(1) print("demo one") def demo_func_two(): ... print("当前线程: ", threading.current_thread()) # <Thread(Th. -
如何在Python中找到线程ID
2021-07-16 12:49:44I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of wh... -
【python】python实现多线程并得到返回值
2022-04-23 02:08:05文章目录一、带有返回值的多线程1.1 实现代码1.2 结果二、实现过程2.1 一个普通的单线程爬虫函数2.2 一个简单的多线程传值实例2.3 实现重点三、代码实战四、学习 一、带有返回值的多线程 1.1 实现代码 # -*- coding... -
python-获取进程id
2021-11-27 14:53:06from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__)... print('process id:', os.getpid()) def f(name): info('\033[31;1mcalled from child process. -
python 多线程
2021-03-06 20:36:02python 多线程真正的多线程吗?对于多核处理器,在同一时间确实可以多个线程独立运行,但在Python中确不是这样的了。原因在于,python虚拟机中引入了GIL这一概念。GIL(Global Interpreter Lock)全局解析器锁是用来... -
Python多线程编程
2021-06-08 15:10:31进程的应用:我们打开的每个软件、游戏,执行的每一个Python脚本都是启动一个进程。 每一个进程像人一样需要吃饭,它的粮食就是CPU和内存。 多进程 同时启动多个软件(进程),多个进程同时在执行程序,他们之间互不... -
python 多线程篇
2022-06-20 13:47:32本文将会介绍 Python 编程语言中多线程处理的基础知识。就像多处理一样,多线程是实现多任务处理的一种方式。在多线程处理中,使用线程的概念。 让我们首先了解计算机体系结构中线程的概念... -
Pyhon 线程里获取操作系统层面的进程 ID 和 线程 ID,太棒了
2020-09-10 11:01:48首先需要说明的是 python threading的name跟ident,这些看起来是线程名字,线程id其实只是个标识,注意是标识而已. 简单过了下threading创建对象及启动线程的代码,发现ident跟pstree查到的线程id是两码事. 该文章... -
python获取进程id_如何在Python中获取正在运行的进程的“父进程” ID?
2020-07-22 09:25:58python获取进程idHow to get the running process’ parent process’ ID in Python? 如何在Python中获取正在运行的进程的“父进程” ID? In Python, you can get the parent process’ pid by calling os.getppid... -
Python使用多线程并获取函数返回值
2021-11-18 10:45:13check_id = self._select_check_id(check_code) one_thread = threading.Thread(target=self._rob, kwargs={'check_id': check_id}) two_thread = threading.Thread(target=self._rob, kwargs={'check_id': check_... -
python封装线程类(启动、终止、查看线程状态)
2021-03-14 10:56:43具体步骤 1.将启动和终止方法封装成类 2.声明时传入要启动的方法 3.通过 start 和 stop 进行启动和终止即可 具体代码如下↓ ... 手动终止线程的方法 ''' def __init__(self, func): self.myThre -
python多线程读取列表
2019-08-07 10:09:46本文代码实现了python多线程读取列表,包括python多线程初始化、开始和释放线程锁、分配多线程列表数等内容,可做参考。 -
python线程基础
2021-04-27 03:20:255 线程实例的属性和方法(getname和setname) name : 线程的名字,只是一个标识,其可以重名,getname() 获取,setname()设置这个名词 ident:线程ID,其是非0整数,线程启动后才会有ID,否则为None,线程退出,此ID... -
超详细,Python 多线程总结的太到位了
2021-10-30 16:28:07B站同名【有温度的算法】已经上线想观看视频讲解的同学在文末点击【原文链接】直达B站多线程常用模板在实际处理数据时,因系统内存有限,我们不可能一次把所有数据都导出进行操作,所以需要批量导出依次操作。... -
Python进程,多进程,获取进程id,给子进程传递参数操作示例
2020-12-25 18:07:54本文实例讲述了Python进程,多进程,获取进程id,给子进程传递参数操作。分享给大家供大家参考,具体如下: 线程与线程之间共享全局变量,进程之间不能共享全局变量。 进程与进程相互独立 (可以通过socket套接字... -
python使用标准库根据进程名如何获取进程的pid详解
2020-12-06 12:53:12特别是有时候需要获取进程的pid,但又无法使用第三方库的时候。下面话不多说了,来一起看看详细的介绍吧。方法适用linux平台.方法1使用subprocess 的check_output函数执行pidof命令from subprocess import check_...