繁体   English   中英

在C中的for循环中创建多个pthread

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM