我正在研究银行家算法并使用循环来创建我的线程。问题是,当应该创建其中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;
}
答案 0 :(得分:2)
如我所见,你的主要内容有一个错误:
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];