Chinaunix首页 | 论坛 | 博客
  • 博客访问: 690608
  • 博文数量: 214
  • 博客积分: 5015
  • 博客等级: 大校
  • 技术积分: 2285
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-18 17:02
文章分类

全部博文(214)

文章存档

2008年(43)

2007年(171)

我的朋友

分类:

2007-12-02 17:23:37

一、首先,简单了解一下多线程,从耳熟能详的fork()、pthread中理点头绪出来,然后自己写一个简单的来增加一下信心。

1、Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。因此,后面的编译必须在选项中加入 -lpthread 选项,否则提示找不到pthread_create()这些函数。

2、pthread_t 是一个线程的标识符,创建线程用pthread_create(),等待线程结束用pthread_join(),这样,差不多就可以开始写第一个简单的多线程程序了,简单得类似HelloWorld

下面的是我自己写的一个最简单的程序。

/////// simpleone.c


      1 #include <stdio.h>
      2 #include <pthread.h>
      3
      4 void thread()
      5 {
      6 int i;
      7 for (i=0;i<3;i++)
      8 {
      9 printf("This is thread %d .\r\n",i);
     10 sleep(i);
     11 }
     12 }
     13
     14 int main()
     15 {
     16 pthread_t id;
     17 int i,ret;
     18 ret = pthread_create(&id,NULL,(void *)thread,NULL);
     19 if (ret != 0)
     20 {
     21 printf("Create thread error!\r\n");
     22 exit(1);
     23 }
     24 for (i=0;i<3;i++)
     25 {
     26 printf("This is the main thread %d .\r\n",i);
     27 sleep(i);
     28 }
     29 pthread_join(id,NULL);
     30 return(0);
     31 }
     32

使用gcc -g -lpthread simpleone.c 编译

使用./a.out运行

结果:

This is thread 0 .
This is thread 1 .
This is the main thread 0 .
This is the main thread 1 .
This is thread 2 .
This is the main thread 2 .

不同的机器运行结果有可能不同,是由于两个“并行”的线程抢夺处理器资源造成的。而sleep(i)是我自作聪明的想法,仅仅是为了让结果看上去更加能体现两个线程是“并行”执行的,其实完全可以省去。

阅读(590) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~