找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3497|回复: 0

[原]linux下的C语言开发(多线程编程)

[复制链接]
发表于 2012-2-7 10:20:47 | 显示全部楼层 |阅读模式
【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

    多线程和多进程还是有很多区别的。其中之一就是,多进程是linux内核本身所支持的,而多线程则需要相应的动态库进行支持。对于进程而言,数据之间都是相互隔离的,而多线程则不同,不同的线程除了堆栈空间之外所有的数据都是共享的。说了这么多,我们还是自己编写一个多线程程序看看结果究竟是怎么样的。#include <stdio.h>
  1. #include <pthread.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. void func_1(void* args)
  5. {
  6.     while(1){
  7.         sleep(1);
  8.         printf("this is func_1!\n");
  9.     }
  10. }
  11. void func_2(void* args)
  12. {
  13.     while(1){
  14.         sleep(2);
  15.         printf("this is func_2!\n");
  16.     }
  17. }
  18. int main()
  19. {
  20.     pthread_t pid1, pid2;
  21.     if(pthread_create(&pid1, NULL, func_1, NULL))
  22.     {
  23.         return -1;
  24.     }
  25.     if(pthread_create(&pid2, NULL, func_2, NULL))
  26.     {
  27.         return -1;
  28.     }
  29.     while(1){
  30.         sleep(3);
  31.     }
  32.     return 0;
  33. }
复制代码

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


[test@localhost Desktop]$ ./threadthis 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!

作者:feixiaoxing 发表于2012-2-6 19:45:46 原文链接

您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-5-1 01:11 , Processed in 0.011264 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表