C語言中程序內可建立的最大執行緒數
給定的任務是找到在 C 語言中程序內可以建立的最大執行緒數。
執行緒是輕量級程序,可以由排程程式獨立管理。因為執行緒是程序的一部分,所以多個執行緒可以關聯到一個程序中,並且由於它比程序更輕量級,因此上下文切換需要更少的時間。
執行緒需要的資源比程序少,並且它們還與同級執行緒共享記憶體。所有使用者級同級執行緒都被作業系統視為單個任務。它們的建立和終止也需要更少的時間。
每次執行程式時,輸出都會有所不同。
下面程式中使用的演算法如下
建立函式 void* create(void *) 並將其留空,因為它只演示了執行緒的工作。
在 main() 函式中初始化兩個變數 max = 0 和 ret = 0,它們都是 int 型別,分別用於儲存最大執行緒數和返回值。
宣告一個 pthread_t 型別的變數“th”。
執行一個 while 迴圈,條件為 ret == 0,並在其中放置 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP