I wondered how should i approach the following problem. My c program will receive 3 arguments - path, term and number of threads to invoke.
I should explore files that contain the term in their name, in any of the sub-directories of the path. If my program would have been asychronous it would have been a rather easy job.
I am using a shared queue for my threads, with a lock and condition variable for synchronization.
My logic goes as follows -
int main(int argc, char *argv)
{
...
Queue *queue = init_queue();
enqueue(queue, root_path);
for (int i = 0; i<n_threads; ++i)
pthread_create(..., thread_handle, ...);
...
}
void thread_handle()
{
while (!queue_empty)
{
while(!condition_variable)
pthread_cond_wait(&cond);
pthread_mutex_lock(&lock);
QNode *node = dequeue(queue);
iterate_dir(node->path);
pthread_mutex_unlock(&lock);
thread_cond_signal(condition_variable);
}
}
void iterate_dir(...)
{
// Directory search logic (with enqueue..)
}
This is rather a psuedo-code than a real code, but I'm more worried about my logic than my implementation. My question is, how can i signal my threads that empty queue signals to end their function, and it's not just temporary until the queue will contain some path.
I would love to hear you opinions!