在 C 中 thread_join 之后重用线程结构

Reuse thread struct after thread_join in C

我在堆栈上有一个线程变量数组,主线程稍后会加入该数组。稍后我必须再次 运行 相同数量的线程,并且想知道我是否仍然可以使用相同的线程结构数组来创建新线程,或者是否不能再次使用线程结构来创建新线程.

像这样:

main_method() {

    pthread_t threads[10]
    for (all threads)
        pthread_create(&threads[i], NULL, some_func, &arg[i])

    for (each thread in threads[10])
        pthread_join(&threads[i]), ...)

    // Does this work?
    for (each thread in threads[10])
        pthread_create(&threads[i], NULL, other_func, &arg[i])

    //Or do I have to do this
    pthread_t threads2[10]

    for (each thread in threads2[10])
        pthread_create(&threads2[i], NULL, other_func, &arg[i])

此处提出了类似的问题,但不确定答案是否解决了上述问题。

How to reuse threads using pthread_exit()

当一个线程退出时,它就完成了。你不能 "reuse" 它 - 创建另一个。您当然可以重用您的数组 - 但不能重用其中的值。 (即需要再次pthread_create)

您引用的问题是询问最大/并发/线程数 - OP 没有加入或退出他的线程。在程序执行的整个生命周期内,您可以使用的线程数没有限制。

你问的是两个实际上不等同的问题。要直接在代码段的注释中回答问题:

// Does this work?
for (each thread in threads[10])
    pthread_create(&threads[i], NULL, other_func, &arg[i])

答案是肯定的,有效。

但它并没有按照您的问题的主题进行操作——它没有重用任何实际的 运行 线程。当您调用 pthread_create() 时,它会创建一个线程并将标识符存储在其第一个参数指向的 space 中。所以你正在重用那个存储来存储一个新的 id,但是你已经创建了一个全新的线程。