0

我正在研究银行家算法并使用循环来创建我的线程。问题是,当应该创建 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;
}
4

1 回答 1

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];

于 2017-03-17T01:51:34.413 回答