Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 当pthread_create()返回时,新线程是否存在?_Linux_Pthreads - Fatal编程技术网

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

Linux 当pthread_create()返回时,新线程是否存在?,linux,pthreads,Linux,Pthreads,我的应用程序使用pthread_create()创建几个线程,然后尝试使用pthread_kill(threadId,0)验证它们的存在。每隔一段时间pthread_kill就会失败,并显示“没有这样的进程” 是不是在pthread_创建之后,我调用pthread_kill太早了?我想,pthread_create()返回的threadId立即有效,但情况似乎并非总是如此 我确实检查了pthread_create()本身的返回值——它没有失败。。。以下是代码片段: if (pthread

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

是不是在pthread_创建之后,我调用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;
    }

偶尔我会收到一条关于线程的消息,它无法发出信号…

这确实是一个实现问题。线程可能存在,也可能仍处于初始化状态,
pthread\u kill
尚未生效

如果您确实想验证线程是否已启动并正在运行,请在线程函数本身中加入某种形式的线程间通信,而不是依赖底层细节

这可以像一个数组一样简单,主线程初始化为某个对象,线程函数将其设置为其他对象作为其第一个操作。类似(显然是伪代码):


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

线程是否已经运行到完成状态?否,它被编码为初始化,然后等待来自主服务器的工作…初始化过程中没有任何类型的错误路径?除非先报告错误,否则不会发生错误…谢谢。是的,我当然可以这样做——使用pthread_yield()而不是sleepABit()。我只是很惊讶,这是必要的。pthread_create()给了我线程ID——但它“还没有”是无效的。哎哟
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.