Linux多線程程編(一)--創建線程


Linux多線程程編已經有成熟的 pthread庫進行支持,首先對多線程程編的常用API進行梳理。

線程

並發性和並行性

在單個處理器的多線程進程中,處理器可以在線程之間切換執行資源,從而執行並發
在共享內存的多處理器的多線程進程中,進程中的每一個線程都可以在一個單獨的cpu上並發執行。

用戶級線程

線程僅在進程內部是可見的,進程內部的線程會共享諸如地址空間、打開的文件等所有進程資源
以下狀態對每一個線程來說是唯一的

  • 線程ID
  • 寄存器狀態
  • 信號掩碼
  • 優先級
  • 線程專用儲存
常用API

線程主要關注的點有三個,線程的創建,線程的退出以及線程等待 ,在linux下需要引用頭文件#include <pthread.h>

創建線程
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,
(void*)(*start_rtn)(void*),void *arg);

編譯鏈接選項
-lpthread,由於pthread庫不是Linux系統的默認庫,而是POSIX的線程庫,因此在編譯的時候需要加上-lpthread或者-pthread來顯示鏈接該庫,函數在執行錯誤的時候並不會修改系統錯誤信息errno而是返回錯誤值。

入參解析
1.pthread_t tidp 線程ID的指針,對於每一個線程來說是唯一的
2.pthread_attr_t attr 此參數為Posix的線程屬性,缺省值為NULL
3.(void
)(
start_rtn)(void*) 線程運行函數的起始地址
4.運行函數的參數,多個參數的時候可以定義結構體

返回值解析
如果創建線程成功,返回0;創建線程失敗返回錯誤的原因;
如果線程創建成功,tidp指向的內存單元被設置為新創建的線程的線程ID

代碼示例

  1 #include<stdio.h>
  2 #include<pthread.h>
  3 #include<string.h>
  4 #include<sys/types.h>
  5 #include<unistd.h>
  6 void* printP(void* arg)
  7 {
  8     int i=0;
  9 
 10     while (i != 100)
 11     {
 12         i++;
 13         printf("This is the %d  times print\n", i);
 14         sleep(1);
 15     
 16     }
 17     
 18 }
 19 
 20 bool CreateThread()
 21 {
 22     pthread_t m_pthread;
 23     printf("This is new  pthread\n");
 24 
 25     //創建線程
 26     if (pthread_create(&m_pthread, NULL, printP, NULL) != 0)
 27     {
 28         return false;
 29     }
 30     return true;
 31 
 32 }
 33 
 34 int  main()
 35 {
 36     if(CreateThread() == false)
 37     {
 38          return -1;
 39     }
 40 
 41     int i = 0;
 42     while(i < 100)
 43     {
 44         i++;
 45         printf("This is the %d times say Hello!\n",i);
 46         sleep(1);
 47     }
 48     return 1;
 49 }           

代碼運行結果

[jager@VM_0_10_centos pthread]$ ./test                                
This is new  pthread
This is the 1 times say Hello!
This is the 1  times print
This is the 2 times say Hello!
This is the 2  times print
This is the 3 times say Hello!
This is the 3  times print
This is the 4 times say Hello!
This is the 4  times print
This is the 5 times say Hello!
This is the 5  times print
This is the 6 times say Hello!

注意
1.線程創建之后,主線程main與pthread線程會交替執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM