【问题标题】:create thread but process shows up?创建线程但出现进程?
【发布时间】:2021-01-28 06:33:17
【问题描述】:
#include <unistd.h>
#include <stdio.h>
#include <cstring>
#include <thread>

void test_cpu() {
    printf("thread: test_cpu start\n");
    int total = 0;
    while (1) {
        ++total;
    }
}

void test_mem() {
    printf("thread: test_mem start\n");
    int step = 20;
    int size = 10 * 1024 * 1024; // 10Mb
    for (int i = 0; i < step; ++i) {
        char* tmp = new char[size];
        memset(tmp, i, size);
        sleep(1);
    }
    printf("thread: test_mem done\n");
}

int main(int argc, char** argv) {
    std::thread t1(test_cpu);
    std::thread t2(test_mem);
    t1.join();
    t2.join();
    return 0;
}

g++ -o test test.cc --std=c++11 -lpthread编译它

我在Linux下运行程序,运行top来监控它。

我希望看到一个进程,但我看到了三个。

看起来std::thread正在创建线程,为什么我最终得到了进程?

【问题讨论】:

  • 是什么让您确定这些是进程而不是线程?使用H 切换top 中的线程显示——有什么变化吗?
  • @G.M.什么...我认为PID意味着进程ID。如何将它们混合在一起.. 好的,非常感谢
  • 附带说明,test_mem() 正在泄漏内存,这是您测试的一部分吗?
  • @RemyLebeau 我不知道。这是借来的代码。感谢您检查。

标签: c++ multithreading process


【解决方案1】:

Linux 不实现线程。它只有轻量级进程(LWP),而 pthread 库将它们包装起来以提供与 POSIX 兼容的线程接口。主 LWP 创建自己的地址空间,而每个后续线程 LWP 与主 LWP 共享地址空间。

许多实用程序,例如 HTOP(似乎在屏幕截图上)默认列出 LWP。为了隐藏线程 LWP,您可以打开 Setup (F2) -> Display Options 并检查 Hide kernel threadsHide userland process threads 选项。还有一个选项可以突出显示线程 - Display threads in different color

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多