I'm having trouble with getting my worker threads and facilitator threads to synchronize properly. The problem I'm trying to solve is to find the largest prime number 10 files using up to 10 threads. 1 thread is single-threaded and anything greater than that is multi-threaded.
The problem lies where the worker signals the facilitator that it has found a new prime. The facilitator can ignore it if the number is insignificant, or signal to update all threads my_latest_lgprime
if it is important. I keep getting stuck in my brain and in code.
The task must be completed using a facilitator and synchronization.
Here is what I have so far:
Worker:
void* worker(void* args){
w_pack* package = (w_pack*) args;
int i, num;
char text_num[30];
*(package->fac_prime) = 0;
for(i = 0; i<package->file_count; i++){
int count = 1000000; //integers per file
FILE* f = package->assigned_files[i];
while(count != 0){
fscanf(f, "%s", text_num);
num = atoi(text_num);
pthread_mutex_lock(&lock2);
while(update_ready != 0){
pthread_cond_wait(&waiter, &lock2);
package->my_latest_lgprime = largest_prime;//largest_prime is global
update_ready = 0;
}
pthread_mutex_unlock(&lock2);
if(num > (package->my_latest_lgprime+100)){
if(isPrime(num)==1){
*(package->fac_prime) = num;
package->my_latest_lgprime = num;
pthread_mutex_lock(&lock);
update_check = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&updater);
}
}
count--;
}
}
done++;
return (void*)package;
}`
Facilitator:
void* facilitator(void* args){
int i, temp_large;
f_pack* package = (f_pack*) args;
while(done != package->threads){
pthread_mutex_lock(&lock);
while(update_check == 0)
pthread_cond_wait(&updater, &lock);
temp_large = isLargest(package->threads_largest, package->threads);
if(temp_large > largest_prime){
pthread_mutex_lock(&lock2);
update_ready = 1;
largest_prime = temp_large;
pthread_mutex_unlock(&lock2);
pthread_cond_broadcast(&waiter);
printf("New large prime: %d\n", largest_prime);
}
update_check = 0;
pthread_mutex_unlock(&lock);
}
}
Here is the worker package
typedef struct worker_package{
int my_latest_lgprime;
int file_count;
int* fac_prime;
FILE* assigned_files[5];
} w_pack;
Is there an easier way to do this using semaphores?