比较线程子进程 占用的内存情况
遇到问题
实际开发中,需要起一个线程进行对定时器处理,这样会处理的及时一些。不会被其它的工作所耽搁。
测试单独的进程占内存情况
#include <stdio.h>
#include <unistd.h>
main()
{
while(1){
sleep(1);
}
return 0;
}
gcc -o test test.c
./ test &
ps aux | grep test
user+ 61035 0.0 0.0 4204 632 pts/6 S 14:57 0:00 ./test
测试带一个线程的进程占用情况
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* thread(void* arg){
while(1){
sleep(1);
}
}
main()
{
pthread_t thread1;
if(pthread_create(&thread1,NULL,thread,NULL) < 0)
perror("pthread_create error");
while(1){
sleep(1);
}
return 0;
}
$ ps aux | grep test1
user+ 61118 0.0 0.0 14704 724 pts/6 Sl 15:07 0:00 ./test1
测试带一个子进程的进程占用情况
#include <stdio.h>
#include <unistd.h>
main()
{
pid_t pid;
pid = fork();
if(-1 == pid)
{
perror("fork error");
}
else if(pid == 0){
while(1){
sleep(1);
}
}else{
while(1){
sleep(1);
}
}
return 0;
}
$ ps aux | grep test2
user+ 27334 0.0 0.0 4204 720 pts/6 S 15:18 0:00 ./test2
user+ 27335 0.0 0.0 4204 80 pts/6 S 15:18 0:00 ./test2
所有的内存信息的统计
说明 | 虚拟内存 | 物理内存 |
---|---|---|
不带线程和子进程 | 4204 | 632 |
创建一个线程的进程 | 14704 | 808 |
创建一个子进程的主进程 | 4204 | 720 |
创建一个子进程的子进程 | 4204 | 80 |
说明:
按实际占用的物理内存来看,加一个线程占用808,加一个子进程的占用720+80 = 800. 感觉都差不多。加子进程的虚内存看着要小一些。