[原创]手把手教你Linux下的多线程设计--Linux下多线程编程详解(一)

来源:互联网 发布:2016社交媒体数据分析 编辑:程序博客网 时间:2024/06/05 09:19

本文可任意转载,但必须注明作者和出处。
【原创】手把手教你Linux下的多线程设计(一)
                                      --Linux下多线程编程详解
原创作者:Frozen_socker(冰棍)  
 E_mail:
dlskyfly@163.com       
 线程也被称为轻权进程(lightweight process)。
 
  在传统的UNIX上,一个进程让另一个实体做某个事务是用fork派生子进程的方法处理的。派生子进程的代价比线程要昂贵得多,尤其是在父子进程之间、子进程之间传递信息需要用IPC或其他方法通信。相对比,使用线程有许多优点,如创建线程要比创建进程快的多、一个进程中的线程共享相同的全局存储区等等。
 
   Linux系统下的多线程遵循POSIX线程接口,称为pthread,在Linux中,多线程需要使用的头文件为<pthread.h>,连接时需要使用库为libpthread.a。
 
 
 
我们编写一个非常简单的例子:
 
//example_1.c
#include <stdio.h>
#include <pthread.h>
 
void * pthread_func_test(void * arg);
 
int main()
...{
     pthread_t pt1,pt2;
     pthread_create(&pt1,NULL,pthread_func_test,"This is the Thread_ONE");
     pthread_create(&pt2,NULL,pthread_func_test,"This is the Thread_TWO");
     sleep(1);              //不加上这句,看不到结果。
}
void * pthread_func_test(void * arg)
...{
     printf("%s /n ",arg);
}
 
 
 
编译源文件:
gcc example_1.c -o example -lpthread
 
 
编译环境:
平   台:FC6
版   本:2.6.18-1.2798.fc6
编译器:gcc 4.1.1 20070105 (Red Hat 4.1.1-51)
 
 
 
 
运行可执行文件:
./example
 
 
 
在终端上的输出结果:
This is the Thread_ONE
This is the Thread_TWO
 
 
  在example_1这个例子中,一共产生了三个线程,第一个就是main所代表的主线程,另外两个就是pt1和pt2分别代表的两个分支线程,这两个线程由pthread_create函数创建,执行的内容就是写在函数pthread_func_test里的东东。
上例涉及到的函数是:pthread_create()
函数原型如下:
int pthread_create(pthread_t *restrict thread,
           const pthread_attr_t *restrict attr,
           void *(*start_routine)(void*), void *restrict arg);
 
 
参数点解:
1、每个线程都有自己的ID即thread ID,可以简称tid,呵呵,是不是想起什么来了?。。。对,和pid有点象。其类型为pthread_t,pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:
         typedef unsigned long int pthread_t;
         可以看成是线程的标志符。当成功创建一个新线程的时候,系统会为该线程分配一个tid,并将该值通过指针返回给调用它的程序。
2、attr申明线程的属性。                       
     属性结构为pthread_attr_t,它在头文件/usr/include/pthread.h中定义。设为NULL,表示在这里我们只使用线程的默认属性就可以了。
    
3、start_routine表示新创建的线程所要执行的例程。线程以调用该函数开始,直到由该函数返回(return)终止这个线程,或者在start_routine所指向的函数中调用pthread_exit函数终止。start_routine只有一个参数,该参数由随后的arg指针来指出。
 
4、arg:也是一个指针,也就是start_routine指针所指向的函数的参数。
 
 
 
返回值:
  当pthread_create调用成功时,该调用返回0;否则,返回一个错误代码指出错误的类型。

       欢迎您发邮件与我交流,但因为工作和时间的关系,我有权对您提出的一些问题不予回答,敬请见谅。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Frozen_fish/archive/2007/07/05/1679491.aspx