我刚刚开始学习 pthreads API,我正在关注这里的教程
但是,在 的示例程序中pthread_create
,示例程序创建一个 long 变量并传递它的值,类型转换为void*
。在线程入口函数中,它像 long 一样取消引用它。
这是合法的吗?我知道如果我传递变量的地址t
,每个线程都将作用于同一个变量而不是它的副本。我们可以这样做吗,因为它是 avoid*
并且编译器不知道我们发送的是什么类型?
#include <pthread.h>
#include <stdio.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);
}
}
pthread_exit(NULL);
}