1

我的应用程序使用 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;
    }

有时我会收到有关线程的消息,但无法发出信号...

4

1 回答 1

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状态来控制主线程何时知道所有其他线程正在做某事,在必要时关闭线程。

于 2013-02-12T07:37:13.560 回答