C语言 如何创建可变数量的 pthread?



我在大学里完成的编程作业的一部分指定:

对于线程,在main()中初始化大量pthread_t*数组,并使用malloc(sizeof(pthread_t)为每个新学生动态创建pthread_t

似乎很简单。我所要做的就是:

pthread_t *pthreadArray = malloc(sizeof(pthread_t) * userInputSize);

以创建可变数量的线程。但是,我们没有得到userInputSize.这怎么可能呢?如果我只是做:

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

那岂不是只给了我一个线程来工作吗?我觉得这一定是编程说明中的一个问题。有什么想法吗?

所以只需按照作业所说的去做:

对于线程,初始化大型pthread_t*数组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;

并为每个新学生动态创建pthread_tmalloc(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++;

请记住在适当的情况下添加错误检查。并在完成所有资源后释放它们。

这包括在调用free(student_threads[i])时设置student_threads[i]=NULL,以便您知道数组中的哪些插槽未使用。

最新更新