简体   繁体   中英

Creating multiple pthreads in a for loop in C

I'm working on the bankers algorithm and am using a loop to create my threads. The issue is that the loop in only creating 4 threads when 5 of them should have been created. I've examined my loop and everything seems correct unless I'm missing something.

/* 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;
}

As I see, there is a bug in your main:

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

In this case, the array threads has a size of 3 items , and your index, from for loop, has a range from 0 to 4 (a size of 5 items) , remember your constant #define NUMBER_OF_CUSTOMERS 5 . I'm surprise that you are getting 4 thread, when it should have created 3 before an memory access violation.

You should redefine the array thread with the correct size, and using the constant NUMBER_OF_CUSTOMERS, as: pthread_t threads [NUMBER_OF_CUSTOMERS];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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