0

我有一个 C++ 程序并在其中使用 pthreads。在这个程序中,线程用于搜索数据中的模式。这是我在程序中的做法:

for (i=0; i<NUM_THREADS; i++) {
    rc = pthread_join(threads[i], NULL);
    assert(0==rc);
    if (args[i].islast == true || args[i].nextaddr != NULL){ //if the pattern is found
        for (j = i+1; j<NUM_THREADS;j++){
            rc = pthread_join(threads[j], NULL); //join the other threads that is not useful
            assert(0 == rc);
        }
        return args[i].nextaddr; //return the address obtained in the thread of interest
    }
}

但是for加入无用线程的第二个循环是昂贵的(程序需要非常快,如果我能避免简单的“for”,这是一个了不起的成就)。

我想知道是否存在可以一次杀死所有子线程的命令。

Ps:我需要“加入”无用的线程。如果我不这样做,那么线程将无法回收,并且一段时间后我会达到线程的限制。

4

1 回答 1

0

您可以使用屏障,而不是使用 for 循环来连接各种线程。

pthread_barrier_t barrier; // the barrier object
pthread_t threads [NUM_THREADS]; // the thread childs.

// create the threads ...

// initialize the barrier like other pthread object.
pthread_barrier_init (&barrier, NULL, NUM_THREADS+1);

请注意,第二个参数是障碍的属性。如果为 NULL,将设置默认属性。第三个参数是将被屏障同步的线程数。每个线程都将调用 pthread_barrier_wait 以等待也将调用相同函数的其他线程。当特定数量的线程在屏障中等待时,所有线程都将被解除阻塞。

我写了 NUM_THREADS+1,NUM_THREADS 是子线程的数量,并将其递增到与主线程一样的计数。

在“重要线程”中,您可以编写类似这样的内容来等待子线程。

/* do important stuff while child threads are executing ... */

/* wait for the childs (join) */
pthread_barrier_wait (&barrier); // main thread gets blocked by the barrier.
                               // untill a specific number of threads reaches the
                               // barrier as well

/* continue execution ... */

在子线程中,添加下一行代码...

void* child_thread_func (void* args)
{
    /* do something with the thread ... */

    /* syncronize with the barrier and exit */
    pthread_barrier_wait (&barrier);

    pthread_exit (some_data);
}

通过这种方式,当孩子将被解除阻塞时,它会立即返回并加入主线程。

不要忘记释放与屏障相关的资源。(仅当任何线程不再使用屏障时)...

pthread_barrier_destroy (&barrier);
于 2013-02-21T16:36:38.810 回答