[英]Creating multiple pthreads in a for loop in C
我正在研究銀行家算法,並且正在使用循環創建我的線程。 問題在於,僅當應創建5個線程時才創建4個線程的循環。 我已經檢查了我的循環,除非缺少任何東西,否則一切似乎都是正確的。
/* these may be any values >= 0 */
#define NUMBER_OF_CUSTOMERS 5
#define NUMBER_OF_RESOURCES 3
/* the available amount of each resource */
int available[NUMBER_OF_RESOURCES];
/*the maximum demand of each customer */
int maximum[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
/* the amount currently allocated to each customer */
int allocation[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
/* the remaining need of each customer */
int need[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
int release_resources(int customer_num, int release[]){
allocation[customer_num][NUMBER_OF_RESOURCES];
return 1;
}
pthread_mutex_t mutex;
int main(int argc, char *argv[]){
pthread_mutex_init(&mutex, NULL);
pthread_t threads [3];
int result;
unsigned index;
for(index = 0; index < NUMBER_OF_RESOURCES; index++){
available[index] = strtol(argv[index+1], NULL,10);
}
for(index = 0; index < NUMBER_OF_CUSTOMERS; ++index){
printf("\nCreating thead %d", index);
result = pthread_create(&threads[index],NULL,release_resources,1);
}
//printf("Done");
return 0;
}
如我所見,您的主程序中存在一個錯誤:
int main(int argc, char *argv[]){
//...
pthread_t threads [3];
int result;
unsigned index;
//...
for(index = 0; index < NUMBER_OF_CUSTOMERS; ++index){
printf("\nCreating thead %d", index);
result = pthread_create(&threads[index],NULL,release_resources,1);
}
//...
return 0;
}
在這種情況下,數組threads
的大小為3個項目 ,而索引(對於for循環) 的范圍為0到4(大小為5個項目) ,請記住常量#define NUMBER_OF_CUSTOMERS 5
。 我很驚訝您獲得4個線程,而該線程應該在發生內存訪問沖突之前創建了3個線程。
您應該使用正確的大小重新定義數組線程,並使用常量NUMBER_OF_CUSTOMERS,如下所示: pthread_t threads [NUMBER_OF_CUSTOMERS];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.