(1)在函数threadFunc
中,它被声明为具有void *
类型,而不是int *
类型
void *threadFunc(void *arg)
{
int loops = *((int *) arg);
printf("the loops value is %d \n",loops);
}
(2)因此,在这个表达式中
int loops = *((int *) arg);
(3)该指针最初再次解释为int *
类型的指针,也就是将void类型的指针强制转换为int类型指针。
(int *) arg
(4)然后,它被解除引用,以获得它所指向的对象。
*((int *) arg)
示例1:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
void *threadFunc(void *arg)
{
int loops = *((int *) arg);
printf("the loops value is %d \n",loops);
}
int main(void )
{
pthread_t t1;
int s=100;
void *thread_result;
s = pthread_create(&t1, NULL, threadFunc, &s);
pthread_join(t1,thread_result);
exit(0);
}
s = pthread_create(&t1, NULL, threadFunc, &s); &s向 threadFunc传递的是整型实参,但是threadFunc中的形参是void指针。在threadFunc中通过将void指针转换为int类型。结果输出的是整型值。
示例2:将void 类型支撑转换为char类型。输出 的结果为Hello World
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
void *threadFunc(void *arg)
{
char* loops = ((char *) arg);
printf("the value of loops is \n");
puts(loops);
}
int main(void )
{
pthread_t t1;
char * s="Hello World \n";
void *thread_result;
pthread_create(&t1, NULL, threadFunc, s);
pthread_join(t1,thread_result);
exit(0);
}