[英]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.
问题在于,仅当应创建5个线程时才创建4个线程的循环。 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
. 在这种情况下,数组
threads
的大小为3个项目 ,而索引(对于for循环) 的范围为0到4(大小为5个项目) ,请记住常量#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. 我很惊讶您获得4个线程,而该线程应该在发生内存访问冲突之前创建了3个线程。
You should redefine the array thread with the correct size, and using the constant NUMBER_OF_CUSTOMERS, as: pthread_t threads [NUMBER_OF_CUSTOMERS];
您应该使用正确的大小重新定义数组线程,并使用常量NUMBER_OF_CUSTOMERS,如下所示:
pthread_t threads [NUMBER_OF_CUSTOMERS];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.