在 C 中将数组传递给 pthread_create

Passing array to pthread_create in C

将数组传递给 pthread_create 的正确方法是什么?我看到的每个地方都是 (void*)myArray) 为什么会这样?为什么我必须放 void*?其他语言的数组名不够用?作为函数参数,为什么 void *add_first_quat(void *a) 为什么我们要放置 void *

您的 start_routine 将采用一个指针,但它不关心在该地址找到的数据类型。因此,它需要一个 void * 并允许您以后随意使用它。

在变量名前使用强制转换 (void *) 只会在编译程序时防止出现警告。

在C语言中,void*只是一个占位符,表示"any pointer"。你的实际数组很可能有不同的类型,这就是为什么你必须转换它以便 pthread_create 可以接受这个参数。

这是因为在 pthread 使用的函数中只能有一个参数,由函数的第四个参数指定 pthread_create,我们可以从手册页中找到共 pthread_create

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
                      void *(*start_routine) (void *), void *arg);

这个参数必须尽可能通用,因为你每次使用该函数时都可以给出不同的参数空指针实际上是没有类型的指针,然后可以使用它们,但是它们应该由具有[=25=的函数使用]适当投.

The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

因为你唯一的参数是一个空指针,你需要每次都将你的参数转换为一个空指针。这不是必需的,但至少是一种习惯,有点类似于使用 malloc.

时的强制转换

你可能会问,如果你想传递多个参数而不是一个参数怎么办?解决这个问题的典型方法是将所有参数封装到 struct 中,然后传递该结构。

(void*)myArray) why is it so? why I have to put void*? Array name is not enough as we do in other languages?

传递给线程函数时不需要转换数组。这可能是由于旧习惯或缺乏理解 void * 与任何其他数据指针兼容。转换充其量是多余的,最坏的情况下可能会导致错误。

这是传递数组的正确方法:

pthread_create(&thrd_id, 0, thread_func, array); 

as a function argument why void *add_first_quat(void *a) why we are putting void *?

因为这是 pthreads 库的线程函数所期望的。原因是它允许您将任何数据指针传递给线程函数(又名 "generic" 指针类型)。假设您有 3 个线程(相同的线程函数)作用于不同类型的 "struct" 数据。

底层OS提供线程支持,OS不关心用什么语言编写它运行的代码。 OS 线程 API 调用必须独立于语言特性,因此 'CreateThread' 调用通常设计为仅将一个指针复制到新线程的堆栈以供线程函数检索当它最终运行时。由 language/code 创建新线程以适当和正确的方式使用该指针。在 C/pthreads 的情况下,此约束表面为 void* 指针。

Everywhere I am seeing is (void*)myArray

好吧,我经常看到一个指向动态分配结构的指针,或者在 OO 语言的情况下,一个对象实例 pointer/ref。我不明白为什么数组指针会是任何类型的 'favoured' 类型。