[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > 其它 > 正文
Linux程式設計- 2.fork, pthread, and signals
http://www.openchess.org/noitatsko/programming/ (2001-05-24 15:00:00)

雖然在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 
(http://www.fanqiang.com)
    進入【UNIX論壇

相關文章
Linux程式設計-31.工作群資訊管理(grp) (2001-05-27 22:08:00)
Linux程式設計-30.使用者資訊管理(pwd) (2001-05-27 21:04:00)
Linux程式設計-29.時間處理 (2001-05-27 20:10:01)
Linux程式設計-28.GNU Make (2001-05-27 19:00:00)
Linux程式設計-27.GNU Debugger (2001-05-27 18:08:01)
Linux程式設計-26.PIPE (2001-05-27 17:04:00)
Linux程式設計-25.Message Queues (2001-05-27 16:10:00)
Linux程式設計-24.Semaphores (2001-05-27 15:00:00)
Linux程式設計-23.共享記憶體(Shared Memory) (2001-05-27 14:08:00)
Linux程式設計-20.getopt (2001-05-27 13:04:00)

===更多相關===
 

★  樊強制作 歡迎分享  ★