linux 线程和进程区别(浅)

16 篇文章 0 订阅

pthread_create() 和 fork() 区别

pthread_create()
// pthread
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

void* child(void *arg){
    printf("child...\n");
    pid_t pid=getpid();
    printf("child: pid = %d\n", pid);
    sleep(1000);
}

void parent(){
    printf("parent...\n");
    pid_t pid=getpid();
    printf("parent: pid = %d\n", pid);
    sleep(1000);
}

void error(){
    perror("fork:");
    exit( -1);
}
int main(){
    pthread_t id;
    pthread_create(&id,NULL, child,NULL);
    printf("new thread id %lu\n",id);
    parent();
    return 0;
}

输出:

new thread id 139976466216704
parent...
parent: pid = 3408
child...
child: pid = 3408
$ ps -ef|grep test4
ubuntu    3408  1244  0 09:27 pts/1    00:00:00 ./test4
ubuntu    3415  1761  0 09:27 pts/10   00:00:00 grep --color=auto test4
fork()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void  child(){
    printf("child...\n");
    pid_t pid=getpid();
    printf("child: pid = %d\n", pid);
    sleep(1000);
}

void parent(){
    printf("parent...\n");
    pid_t pid=getpid();
    printf("parent: pid = %d\n", pid);
    sleep(1000);
}

void error(){
    perror("fork:");
    exit( -1);
}
int main(){
    int pid;
    pid=fork();
    if(pid==0){
        child();
    }else if(pid>0){
        printf("child process id %d\n",pid);
        parent();
    }else{
        error();
    }
    return 0;
}
new process id 3318
parent...
parent: pid = 3317
child...
child: pid = 3318
$ ps -ef|grep test3
ubuntu    3317  1244  0 09:26 pts/1    00:00:00 ./test3
ubuntu    3318  3317  0 09:26 pts/1    00:00:00 ./test3
ubuntu    3351  1761  0 09:26 pts/10   00:00:00 grep --color=auto test3

所以如果不去深究内部的实现机制,那么从外面看,thread 和 process 还是可以套用经典的操作系统的概念的。
另外一点,pthread 的代码编译时要加上-lpthread,而 fork 则不用去额外链接库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值