【发布时间】:2016-01-14 11:31:10
【问题描述】:
我正在尝试了解 pthreads,并且正在编译我在网上找到的程序。
#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
非常感谢大家!
【问题讨论】:
-
你确实知道指针是如何声明的吗?你确实知道通用指针
void *吗?现在再次查看PrintHello函数声明。如果你不知道通用指针,现在是时候去你最喜欢的搜索引擎做一些搜索了。