要等待IN线程完成的唯一同步对象

时间:2013-03-05 12:32:00

标签: c++ multithreading synchronization thread-safety

我有一个Threadpool类,这个类有一个wait()方法。现在,该类可以创建N个线程,和 创建线程时,其句柄将插入到容器中 我用来实现wait()函数的经典方法是遍历容器并等待 一个句柄,像这样:

thread_handle_iterator th = get_first_thread_handle_iterator();
thread_handle_iterator th2 = get_last_thread_handle_iterator();

while (th != th2)
{
     joint(*th);
     ++th;
}

这完美无缺。现在,我没有这个循环,而是拥有一个原子计数器 每个线程开始运行时递增,然后在线程结束时递减 跑步。当count == 0 [最后一个线程正在完成]时,会触发事件[或posix中的条件变量]。 像这样:

int
thread_entrypoint(Threadpool * p)
{
    int result;
    p->atomic_thread_count.add();
    result = p->getRunnable()->run();  // execute the thread code.
    if (p->atomic_thread_count.fetchAndAdd(-1) == 1) // this is the last thread!
    {
           p->event.signal(); // fires the event/condition variable
    }
    return result; // the thread returns the result and exits.
}

所以,基本上这样我就不会有一个恼人的容器,我可以在创建时分离所有线程 他们:这将简化我的代码。然后,即使Threadpool的线程被分离, 我仍然可以等完成,只需拨打Threapool::wait() { event.wait(); }

即可

另外,我的优点是我可以添加一个全局原子计数器,所以我可以等待每个线程 由每个 Threadpool实例创建,如下所示:

AtomicInt global_threads_count;
WaitEvent global_all_threads_exited_event;

int
thread_entrypoint(Threadpool * p)
{
    int result;
    p->atomic_thread_count.add();
    global_threads_count.add();

    result = p->getRunnable()->run();  // execute the thread code.
    if (p->atomic_thread_count.fetchAndAdd(-1) == 1) // this is the last thread!
    {
           p->event.signal(); // fires the event/condition variable
    }

    if (global_threads_count.fetchAndAdd(-1) == 1) // this is the last thread of *ALL* threads!
    {
           global_all_threads_exited_event.signal(); // fires the event/condition variable
    }
    return result; // the thread returns the result and exits.
}

我可以通过调用Threapool::waitForAllThreads() { global_all_threads_exited_event.wait(); }

等待所有线程完成

- 这是一种可靠,快速,有效的设计吗?

0 个答案:

没有答案