进程:
- 资源管理的最小单位,独占内存空间
线程:
- 调度的最小单位,在进程中创建,共享内存空间。
函数调用
步骤 | 线程 | 进程 |
---|---|---|
创建 | pthread_create | fork |
退出 | pthread_exit/pthread_cancel | exit/__exit |
等待 | pthread_join | wait |
#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#