理解 pthread 上的困难

Understanding difficulties on pthread

我正在尝试了解 pthreads,并且正在编译我在网上找到的程序。

Here is a simple one

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0;t<NUM_THREADS;t++){
     printf("In main: creating thread %ld\n", t);
     rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
     if (rc){
       printf("ERROR; return code from pthread_create() is %d\n", rc);
       exit(-1);
       }
     }

   /* Last thing that main() should do */
   pthread_exit(NULL);
}

所以我无法理解 PrintHello 函数的语法。

1)“*PrintHello”函数名有点像 o 指针(因为星号)?

2)函数的参数是一个没有类型的指针?所以...甚至没有指针?

3)我们如何将变量的 void 类型 转换为 long 类型?

难道我们不能构建一个更简单的函数并在线程中传递它吗?

4)最后在main中,在pthread函数中,(void *)t参数是什么意思? :O

非常感谢你们!

PrintHello() 是一个 函数 接受一个 void* 参数并返回一个 void* 值。

如果仍有疑问,请阅读 Kernighan and Ritchie 以学习 C 编程。

在深入并行之前,你应该学习一点C语言。这样你的学习就会轻松很多: void pointer 是通用指针。查看 this 关于 void 指针的教程。

1)The "*PrintHello" function name is something like a pointer(because of the star symbol)?

它是函数,返回指向 void 的指针。即 void *.

2)The function's parameter is a pointer with no type? So... not even a pointer?

没错。线程函数一个空指针。

3)How can we cast a void type of variable into a long?

这是指针类型到整数类型的转换。此转换是 implementation-defined 并且可能 未定义。 这将适用于当今的大多数实现,但绝不是完全可移植的。

4) Are we not able to build a simpler function and pass it in the thread?

没有。因为 pthread_create() 函数特别需要一个带有 void* 参数和 returns void* 的函数指针。所以你不能传递一个不同的函数。

5) At last in main, at pthread function, what does the (void *)t parameter means?

这是整数到指针的转换。 (3) 中的相同评论也适用于此。

1: Thread functions need to have a void* return type as a void pointer can be used to point to any piece of data in memory.

2: Yes that's correct.

3: This is a conversion from a pointer to an int.

4: This is a int to pointer conversion.

你应该读一些关于线程的基础教程和一些关于 C 的书。