首頁  >  文章  >  後端開發  >  在C語言中,一個行程內可以建立的最大執行緒數

在C語言中,一個行程內可以建立的最大執行緒數

王林
王林轉載
2023-09-17 21:49:031238瀏覽

在C語言中,一個行程內可以建立的最大執行緒數

給定的任務是在一個行程中找到可以建立的最大執行緒數

C.

執行緒是輕量級進程,可以由調度程式獨立管理。因為一個 執行緒是進程的一個元件,因此可以關聯多個執行緒

執行緒相對於進程而言,不僅處理起來更輕,而且上下文切換所需時間更短。

執行緒所需的資源較進程少,而且它們也與其同級共享記憶體。

線程。所有使用者級對等執行緒都被作業系統視為單一任務。較少的 它們的創建和終止都需要時間。

每次執行程式時,輸出總是不同的。

下面的程式中使用的方法如下

  • 建立函數 void* create(void *) 並將其留空,因為它只會示範

  • 在 main() 函數中初始化兩個 int 類型的變數 max = 0 和 ret = 0 分別儲存最大線程數和返回值。

  • 宣告一個pthread_t類型的變數「th」。

  • 執行條件 ret == 0 的 while 迴圈並放置 ret = pthread_create (&th, NULL, create, NULL);

  • 在循環內迭代 max 。

  • 在循環外列印 max。

    >

範例

#include<pthread.h>
#include<stdio.h>
/*Leave the function empty as it
only demonstrates work of thread*/
void *create ( void *){
}
//main function
int main(){
   int max = 0, ret = 0;
   pthread_t th;
   //Iterate until 0 is returned
   while (ret == 0){
      ret = pthread_create (&th, NULL, create, NULL);
      max++;
   }
   printf(" %d ", max);
}

輸出

5741

以上是在C語言中,一個行程內可以建立的最大執行緒數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除