Linux 进程 vs 线程

本文通过两个示例程序详细介绍了如何使用C语言进行进程和线程的创建与管理,包括进程间的父子关系、线程取消及同步机制。通过具体代码展示了fork函数创建子进程和pthread库函数创建线程的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

进程:
  • 资源管理的最小单位,独占内存空间
线程:
  • 调度的最小单位,在进程中创建,共享内存空间。

函数调用

步骤线程进程
创建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# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值