Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117110
  • 博文数量: 61
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 230
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-26 11:35
个人简介

实践Linux的理论

文章存档

2015年(1)

2014年(60)

我的朋友

分类: C/C++

2014-04-29 21:23:41

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

阅读(630) | 评论(0) | 转发(0) |
0

上一篇:线程等待

下一篇:进程-管道通信

给主人留下些什么吧!~~