logo

Navigation:First_Community->Software->Linux development Goto:New TopicSettingSearch
Linux程式设计- 2.fork, pthread, and signals
Posted by: imac Date: March 29, 2008 02:02AM

MegaEntry - Social networking and discussion site!

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

MegaEntry - Social networking and discussion site!

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

MegaEntry - Social networking and discussion site!

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); 

CopyRight owned by the original author.--(www.MegaEntry.com)

void pthread_exit(void *retval);  int pthread_attr_init(pthread_attr_t *attr);  资料结构 typedef struct  {    int detachstate; 

MegaEntry - Social networking and discussion site!

  int schedpolicy;    struct sched_param schedparam;    int inheritsched;    int scope;  } pthread_attr_t;  例一:

MegaEntry - Social networking and discussion site!

#include   #include   #include   #include   void * mythread(void *arg)  { 

CopyRight owned by the original author.--(www.MegaEntry.com)

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

CopyRight owned by the original author.--(www.MegaEntry.com)

}  void main(void)  {    pthread_t th; 

CopyRight owned by the original author.--(www.MegaEntry.com)

  if (pthread_create(&th,NULL,mythread,NULL)!=0) exit(0);    for (;;) {      printf( "main process ");      sleep(3);    } 

CopyRight owned by the original author.--(www.MegaEntry.com)

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

MegaEntry - Social networking and discussion site!

thread  thread  main process  thread  thread  thread 

MegaEntry - Social networking and discussion site!

main process  thread  thread  thread  main process 

CopyRight owned by the original author.--(www.MegaEntry.com)



Reply To This Message
Subject: 

Copyright 2005-2006 megaentry,All Rights Reserved
IE 6.0 or above is perfect