【发布时间】: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