Я борюсь с программой, которая использует pthreads. Вот упрощенная версия кода, с которым я сталкиваюсь с трудностями:
#include <cstdlib>
#include <iostream>
#include <pthread.h>
pthread_t* thread_handles;
pthread_mutex_t mutex;
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
int thread_count;
const int some_count = 76;
const int numb_count = 5;
int countR = 0;
//Initialize threads
void InitTh(char* arg[]){
/* Get number of threads */
thread_count = strtol(arg[1], NULL, 10);
/*Allocate space for threads*/
thread_handles =(pthread_t*) malloc (thread_count*sizeof(pthread_t));
}
//Terminate threads
void TermTh(){
for(long thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
free(thread_handles);
}
//Work for threads
void* DO_WORK(void* replica) {
/*Does something*/
pthread_mutex_lock(&mutex);
countR++;
if (countR == numb_count) pthread_cond_broadcast(&cond_var);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
//Some function
void FUNCTION(){
pthread_mutex_init(&mutex, NULL);
for(int k = 0; k < some_count; k++){
for(int j = 0; j < numb_count; j++){
long thread = (long) j % thread_count;
pthread_create(&thread_handles[thread], NULL, DO_WORK, (void *)j);;
}
/*Wait for threads to finish their jobs*/
while(pthread_cond_wait(&cond_var,&mutex) != 0);
countR = 0;
/*Does more work*/
}
pthread_cond_destroy(&cond_var);
pthread_mutex_destroy(&mutex);
}
int main(int argc, char* argv[]) {
/*Initialize threads*/
InitTh(argv);
/*Do some work*/
FUNCTION();
/*Treminate threads*/
TermTh();
pthread_exit(NULL);
}
Когда some_count
(в данном конкретном случае) меньше 76, программа работает нормально, но если я укажу большее значение, программа будет работать некоторое время, а затем останавливается. Может кто-нибудь подскажет, что я делаю не так?
P.S. это мой первый пост такого рода, и я, очевидно, новичок, поэтому, пожалуйста, будьте снисходительны. :)