怎么用脚本获取当前线程数

wen 实用脚本 4

本文目录导读:

怎么用脚本获取当前线程数

  1. Python
  2. Java (通过JVM)
  3. Linux/Unix Shell
  4. C/C++
  5. Node.js
  6. Windows PowerShell
  7. Go语言

Python

import threading
import time
# 获取当前活动线程数
thread_count = threading.active_count()
print(f"当前线程数: {thread_count}")
# 获取所有活动线程的详细信息
for thread in threading.enumerate():
    print(f"线程名: {thread.name}, ID: {thread.ident}")

Java (通过JVM)

# 使用jstack命令
jstack <pid> | grep -c "Thread"
# 或使用jconsole/JMX

Linux/Unix Shell

# 查看特定进程的线程数
ps -T -p <pid> | wc -l
# 或者
cat /proc/<pid>/status | grep Threads
# 查看系统总线程数
ps -eLf | wc -l

C/C++

#include <pthread.h>
#include <stdio.h>
// Linux下获取当前进程线程数
void get_thread_count() {
    char buf[1024];
    FILE *fp = fopen("/proc/self/status", "r");
    if (fp) {
        while (fgets(buf, sizeof(buf), fp)) {
            if (strncmp(buf, "Threads:", 8) == 0) {
                printf("线程数: %s", buf + 8);
                break;
            }
        }
        fclose(fp);
    }
}

Node.js

const v8 = require('v8');
const os = require('os');
// Node.js本身是单线程,但可以获取工作线程数
const worker_threads = require('worker_threads');
if (worker_threads.isMainThread) {
    console.log('主线程');
    console.log('CPU核心数:', os.cpus().length);
}
// 获取进程中的V8线程信息
console.log('V8堆统计:', v8.getHeapStatistics());

Windows PowerShell

# 查看特定进程的线程数
(Get-Process -Name "processname").Threads.Count
# 查看所有进程线程总数
(Get-Process).Threads.Count

Go语言

package main
import (
    "fmt"
    "runtime"
)
func main() {
    // 获取当前goroutine数量
    fmt.Printf("当前goroutine数: %d\n", runtime.NumGoroutine())
    // 获取GOMAXPROCS设置
    fmt.Printf("GOMAXPROCS: %d\n", runtime.GOMAXPROCS(0))
}

注意

  • 不同语言/平台的线程模型不同
  • 有些语言(如Node.js)本身是单线程,但可能有工作线程
  • 生产环境建议使用监控工具而非手动获取线程数

需要针对特定场景的实现吗?

抱歉,评论功能暂时关闭!