您的位置:首页 > 运维架构 > Linux

Linux 进程 vs 线程

2017-04-09 08:55 204 查看

进程:

资源管理的最小单位,独占内存空间

线程:

调度的最小单位,在进程中创建,共享内存空间。

函数调用

步骤线程进程
创建pthread_createfork
退出pthread_exit/pthread_cancelexit/__exit
等待pthread_joinwait
#include <stdio.h>
#include <pthread.h>
//并发:多线程
void *thread(void *st){
while(1){
printf("%d\n",st);
sleep(1);
}
pthread_exit(NULL);
}
int main(int argc,char **argv)
{
pthread_t tid[11];
int i;
for(i = 1; i <= 10; i++){
pthread_create(tid+i,NULL,thread,(void*)i);
}
sleep(5);
pthread_cancel(tid[1]);
pthread_cancel(tid[3]);
pthread_cancel(tid[5]);
pthread_cancel(tid[7]);
pthread_cancel(tid[9]);

pthread_join(tid[2],NULL);

}


运行

root@ubuntu:/home/Desktop/pthread# gcc pthread_create.c -lpthread
root@ubuntu:/home/Desktop/pthread# ./a.out
7
6
8
5
9
4
10
3
2
1


#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv)
{
pid_t pid;
pid = fork();
//
if(pid < 0){
perror("fork:");
return 0;
//exit
//_exit
}
if(pid > 0){    //父进程
printf("%d:HELLO WORLD!\n",getpid());
wait(NULL);//清理子进程(僵尸进程)
sleep(5);
}
else if(pid == 0){//子进程
printf("%d:hello world!\n",getpid());
return 0;
}

//
return 0;
}


运行

root@ubuntu:/home/Desktop/fork# gcc fork.c
root@ubuntu:/home/Desktop/fork# ./a.out
6326:HELLO WORLD!
6327:hello world!
root@ubuntu:/home/Desktop/fork#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux 线程 进程