当pthread_create()返回时,新线程是否存在?

时间:2013-02-12 07:26:43

标签: linux pthreads

我的应用程序使用pthread_create()创建多个线程,然后尝试使用pthread_kill(threadId,0)验证它们的存在。每隔一段时间pthread_kill就会失败并且“没有这样的过程”......

可能是,我在pthread_create之后过早地调用了pthread_kill 吗?我想,pthread_create()返回的threadId立即生效,但似乎并非总是如此......

我确实检查了pthread_create()本身的返回值 - 它没有失败......这是代码片段:

    if (pthread_create(&title->thread, NULL,
        process_title, title)) {
        ERR("Could not spawn thread for `%s': %m",
            title->name);
        continue;
    }
    if (pthread_kill(title->thread, 0)) {
        ERR("Thread of %s could not be signaled.",
            title->name);
        continue;
    }

有一段时间我收到有关线程的消息,无法发出信号......

1 个答案:

答案 0 :(得分:2)

这确实是一个实施问题。线程可能存在,或者它可能仍处于初始化状态,pthread_kill尚未生效。

如果确实想要验证线程是否正常运行,请在线程函数本身中放置某种形式的线程间通信,而不是依赖于底层细节。

这可以像主线程初始化为某个东西的数组一样简单,并且线程函数将其设置为其他东西作为其第一个动作。像(伪代码显然):

array running[10]

def threadFn(index):
    running[index] = stateBorn
    while running[index] != stateDying:
        weaveYourMagic()
    running[index] = stateDead
    exitThread()

def main():
    for i = 1 to 10:
        running[i] = statePrenatal
        startThread (threadFn, i)
    for i = 1 to 10:
        while running[i] != stateBorn:
            sleepABit()

    // All threads are now running, do stuff until shutdown required.

    for i = 1 to 10:
        running[i] = stateDying

    for i = 1 to 10:
        while running[i] != stateDead:
            sleepABit()

    // All threads have now exited, though you could have
    // also used pthread_join for that final loop if you
    // had the thread IDs.

从上面的代码中,您实际上使用running状态来控制主线程何时知道所有其他线程正在执行某些操作,以根据需要关闭线程。