代码中的并行线程

Parrallel Threads In Code

我最近一直在学习线程,我正在尝试计算以下代码的最大并行线程数 运行。

void thread_function2(void*) {
    arbitrary_function();
}

void thread_function1(void*) {
    pthread_t thread_info2;
    pthread_create(&thread_info, NULL, thread_function2, NULL);
    thread_function2(NULL);
    pthread_join(thread_info2, NULL);
}

int main(void) {
    pthread_t thread_info;
    pthread_create(&thread_info, NULL, thread_function1, NULL);
    thread_function1(NULL);
    pthread_join (thread_info, NULL);
}

到目前为止我发现的是主线程创建第一个线程,然后第一个线程创建第二个线程。我知道 pthread_join 会阻塞调用线程,直到指定的线程终止。在这种情况下,这是否意味着 none 个线程是 运行 并行的?有什么想法吗?

你拥有的不止于此。假设您的 arbitrary_function 需要相当长的时间来执行。

首先 main() 创建一个线程,你有 2 个。比第二个创建第三个,并等待它 - 你现在有 3 个。同时,main() 继续,并直接运行 thread_function1 - 这会创建另一个线程。所以在这里你有 4 个。这是最大数量,你不会超过这个数量。