gpt4 book ai didi

c - 如何创建可变数量的pthread?

转载 作者:行者123 更新时间:2023-12-03 12:58:52 24 4
gpt4 key购买 nike

我在大学里有一部分编程任务指定:

for the threads, initialize a large array of pthread_t* in main() and dynamically create pthread_t for each new student using malloc(sizeof(pthread_t).



似乎很简单。我所要做的就是:
pthread_t *pthreadArray = malloc(sizeof(pthread_t) * userInputSize);

创建可变数量的线程。但是,我们没有得到 userInputSize。那怎么可能呢?如果我要这样做:
pthread_t *pthreadArray = malloc(sizeof(pthread_t));  

那不会只给我一个pthread来工作吗?我觉得这一定是编程说明中的一个问题。有任何想法吗?

最佳答案

因此,按照作业说明进行操作即可:

for the threads, initialize a large array of pthread_t* in main()


/* Large number */
const size_t max_threads = 100;

/* Large array of pointers with every element initialized to zero */
pthread_t *student_threads[max_threads] = {};

size_t thread_count = 0;

and dynamically create pthread_t for each new student using malloc(sizeof(pthread_t))


pthread_t *new_student = malloc(sizeof(pthread_t));

没有写的是对 new_student的处理方式。它确实是指向单个 pthread_t的指针。只需将指针放在数组中下一个未使用的插槽中即可:
/* Find next unused spot in array (with value==NULL) */
size_t i = 0
while (i < max_threads && student_threads[i])
i++;

/* assign value to that spot */
student_threads[i] = new_student;
thread_count++;

请记住在适当的地方添加错误检查。完成后释放所有资源。

这包括在每次调用 student_threads[i]=NULL时都设置 free(student_threads[i]),以便知道阵列中哪些插槽未被使用。

关于c - 如何创建可变数量的pthread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666864/

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