gpt4 book ai didi

c - 多线程文件搜索

转载 作者:行者123 更新时间:2023-11-30 14:32:57 25 4
gpt4 key购买 nike

我想知道我应该如何解决以下问题。我的 c 程序将接收 3 个参数 - 要调用的路径、术语和线程数

我应该在路径的任何子目录中探索名称中包含术语的文件。如果我的程序是异步的,那将是一项相当容易的工作。

我的线程使用共享队列,并使用条件变量进行同步。

我的逻辑如下 -

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..)
}

这更像是伪代码而不是真正的代码,但我更担心我的逻辑而不是我的实现。我的问题是,我如何向我的线程发出空队列信号以结束其功能,并且它不仅仅是临时的,直到队列将包含某些路径。

很想听听您的意见!

最佳答案

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.

我认为您是在问如何处理队列为空并不构成适当的线程终止条件这一事实,因为新目录可能会被任何仍处于事件状态的线程排队。答案很简单:不要使用队列空作为(唯一)终止条件。相反,维护另一个共享变量来跟踪当前处理目录的线程数(也在互斥体的保护下),并使循环终止条件为队列为空并且没有线程正在处理目录.

另请注意,您必须

  • 注意确保对共享状态的所有访问都受到互斥锁的保护。在循环条件中包括队列空性测试。
  • 注意尽可能限制互斥量的范围,以便允许最大的并发量。
  • 准备好处理虚假唤醒。

逻辑可能看起来更像是这样:

// ...

int num_active_threads = 0;

void *thread_handle(void *arg) {
pthread_mutex_lock(&lock);
while (true) {
while (queue_empty && num_active_threads > 0) {
pthread_cond_wait(&cond);
}
if (queue_empty) break; // it must (also) be that num_active_threads == 0, so all done
QNode *node = dequeue(queue);
num_active_threads++;
pthread_mutex_unlock(&lock);

iterate_dir(node->path);

pthread_mutex_lock(&lock);
num_active_threads--;
pthread_cond_broadcast(condition_variable);
}
pthread_mutex_unlock(&lock);
}

void iterate_dir(...)
{
// Directory search logic (with MUTEX-PROTECTED enqueue..)
}

关于c - 多线程文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59601056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com