Linux下的C语言开发(多线程编程)



多线程和多进程还是有很多区别的。其中之一就是,多进程是linux内核本身所支持的,而多线程则需要相应的动态库进行支持。对于进程而言,数据之间都是相互隔离的,而多线程则不同,不同的线程除了堆栈空间之外所有的数据都是共享的。说了这么多,我们还是自己编写一个多线程程序看看结果究竟是怎么样的。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

void func_1(void* args)
{
    while(1){
        sleep(1);
        printf("this is func_1!\n");
    }
}

void func_2(void* args)
{
    while(1){
        sleep(2);
        printf("this is func_2!\n");
    }
}

int main()
{
    pthread_t pid1, pid2;

    if(pthread_create(&pid1, NULL, func_1, NULL))
    {
        return -1;
    }

    if(pthread_create(&pid2, NULL, func_2, NULL))
    {
        return -1;
    }

    while(1){
        sleep(3);
    }

    return 0;
}

和我们以前编写的程序有所不同,多线程代码需要这样编译,输入gcc thread.c -o thread -lpthread,编译之后你就可以看到thread可执行文件,输入./thread即可。

[test@localhost Desktop]$ ./thread
this is func_1!
this is func_2!
this is func_1!
this is func_1!
this is func_2!
this is func_1!
this is func_1!
this is func_2!
this is func_1!
this is func_1!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值