gpt4 book ai didi

c++ - 使用 pthread_create() 创建超过 1000 个线程

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:59 26 4
gpt4 key购买 nike

我正在尝试使用 pthread_create() 函数创建 1000 个线程。

这是我正在使用的语句:

for (int i=0 ; i <1000; i++)
{
retValue = pthread_create(&threadId, NULL, simplethreadFunction, NULL);
}

每次这个 for 循环运行时它都会创建一个新线程吗?

这很简单。但我无法理解。

最佳答案

Everytime this for-loop runs does it create a new thread?

是的,确实如此。

This is a simple thing. But I'm unable to understand it.

我再补充几点:

  1. 函数 pthread_create 的第一个参数是指向 pthread_t 的指针类型。基本上,您将一个地址传递给此函数,此函数使用该地址来分配“某物”。

    当此函数创建线程时,会为该线程创建一个“不透明的唯一标识符”,并使您传递的指针指向此位置,以便您以后可以在需要时访问它。

  2. 如果您将同一个指针传递所有 1000 次,您将只能访问在所有 1000 个线程中创建的一个(最后一个)线程的唯一标识符,因为每次前一个值都会超过写的。

  3. 如果您想在线程上执行更多操作(如加入等),则需要此唯一值。

  4. 有关此函数和其他线程相关函数的详细信息,您可以访问 thisthis .

  5. 不要忘记在主上下文中调用 pthread_exit,否则整个程序(包括创建的线程)可能会在所有线程完成之前终止。

关于时间,据我所知,这件事可能不会对创建时间产生任何影响,只会降低您创建的线程的可用性。此外,这次您计算的时间不是创建 1000 个线程的时间,这将取决于许多其他因素,例如平台/实现等。

关于c++ - 使用 pthread_create() 创建超过 1000 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13190910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com