当前位置--> 首 页 --> 文 章 -->Linux Develop

※阅读文章※

Linux程式设计- 2.fork, pthread, and signals


作者:不祥 [文章出自: www.fanqiang.com]


虽然在UNIX下的程式写作,对thread的功能需求并非很大,但thread在现代的作业系统中,几乎都已经存在了。pthread是Linux上的thread函数库,如果您要在Linux下撰写多线程式,例如MP3播放程式,熟悉pthread的用法是必要的。 
有关thread写作,有两本很好的书: 
Programming with POSIX Threads 
Multithreading Programming Techniques 
另外有一份初学者的参考文件Getting Started With POSIX Threads 

pthread及signal都可以用一大章来讨论。在这里,我只谈及最简单及常用的技巧,当您熟悉这些基本技巧的运用後,再找一些专门深入探讨pthread及signal程式写作的书籍来研究。这些进阶的写法,用到的机会较少,将层次分明,学习速度应该会比较快。 



--------------------------------------------------------------------------------

thread
我假设您对thread已经有一些基本的概念,因此,在此我将着重於如何实作。 
函数宣告
int  pthread_create(pthread_t  *  thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); 
int pthread_join(pthread_t th, void **thread_return); 
int pthread_detach(pthread_t th); 
void pthread_exit(void *retval); 
int pthread_attr_init(pthread_attr_t *attr); 
资料结构
typedef struct 

  int detachstate; 
  int schedpolicy; 
  struct sched_param schedparam; 
  int inheritsched; 
  int scope; 
} pthread_attr_t; 
例一:
#include  
#include  
#include  
#include  
void * mythread(void *arg) 


  for (;;) { 
    printf("thread\n"); 
    sleep(1); 
  } 
  return NULL; 


void main(void) 

  pthread_t th; 

  if (pthread_create(&th,NULL,mythread,NULL)!=0) exit(0); 

  for (;;) { 
    printf("main process\n"); 
    sleep(3); 
  } 


执行结果:
./ex1 
main process 
thread 
thread 
thread 
main process 
thread 
thread 
thread 
main process 
thread 
thread 
thread 
main process 

文章加入时间: 2004-11-17 14:56:32 责任编辑: w9   (3044 人次查阅)
 
Copyright © 1998-2004 中国PHP联盟 All rights reserved.