陈毅怎么死的:linux线程库

来源:百度文库 编辑:九乡新闻网 时间:2024/04/19 19:54:33

简单地讲,进程是资源管理的最小单位,线程是程序执行的最小单位.一个进程至少要一个线程作为它的指令执行体,进程管理着资源(比如CPU,内存,文件等),而将线程分配到某个CPU上执行.一个进程当然可以拥有多个线程.

现在有3种不同标准的线程库:WIN32,OS/2和POSIX.(portable operating system interface standard,可移植操作系统接口标准).linux下多线程遵循POSIX接口,称为pthread.

(1)pthread_create()创建新的线程(与fork()类似)

int pthread_create(pthread_t   thread,const pthread_attr_t *attr,void *(*func)(void *),void *arg)

第一个参数是一个pthread_t型的指针用于保存线程ID,以后对该线程的操作都要用ID来标示,每个线程都有同时具有线程ID和进程ID,其中进程ID就内核所维护的进程号,而线程ID则由linuxthreads分配和维护.

第二个参数是一个pthread_attr_t的指针用于说明要创建的线程的属性,使用null表示要使用缺省的属性.

第三个参数指明线程运行函数的起始地址,是一个只有一个(void *)参数的函数.

第四个参数指明了运行函数的参数,参数arg 指向一个结构.

创建线程成功后,新创建的线程则运行参数3和参数4确定的函数,原来的线程则继续运行下一行码.

(2)pthread_join()等待线程结束

pthread_join用来挂起当前线程直到由参数thread指定和线程终止为止,

int pthread_join(pthread_t thread ,void * *status)

第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储等待线程式的返回值.

(3)pthread_t pthread_self(void)

返回本线程的ID

(4)int pthread_detach(pthread_t thread)函数返回值为整数,用于将处于连接的线程变成为脱离状态.

(5)pthread_exit(void *status)用业终止线程,status指向线程返回值的指针.

例:

       1#include
      2 #include
      3 #include
      4 void * thread_function(void * arg)
      5 {
      6         int i;
      7         for( i=0;i<20;i++)
      8         {
      9                 printf(" This is a thread!\n");
     10                 }
     11            return NULL;
     12 }
     13 int main(void)
     14 {
     15         pthread_t mythread;
     16         if( pthread_create( &mythread, NULL,thread_function, NULL))
     17         {
     18                 printf("error creating thread.");
     19                 abort();
     20         }
     21 printf(" This is main process!\n") ;
     22 if ( pthread_join ( mythread,NULL))
     23 {
      24         printf("error joining thread.");
     25         abort();
     26 }
     27 exit(0);
     28 }

编译并执行该程序:

#gcc -lpthread -o mythread mythread.c

#./mythread