The problem of passing parameters to the pthread_create() function
According to my attempts, the thread function must pass in parameters when it is defined, and the fourth parameter can be filled with NULL when it is used.
void *func(void *t)
{
printf("hello world!\n");
//参数*t不使用
}
int main()
{
pthread_t t;
pthread_create(&t,NULL,func,NULL);
//第四个参数不填
pthread_join(t,NULL);
return 0;
}
When passing in a specific integer value, there are two ways.
void *func(void *t)
{
printf("This value is %d\n",*(int *)t);
}
int main()
{
int value=5;
pthread_t t;
pthread_create(&t,NULL,func,&value);
//将value的地址传过去.
pthread_join(t,NULL);
return 0;
}
This method has a drawback, because it is the incoming address, the t value in the thread function will be modified along with the value of value.
The second method:
The second method has been pondering for a long time, because it keeps reporting errors when compiling, and later I figured out the reason for the 64-bit machine.
#define TYPE32 int
#define TYPE64 long
void *func(void *t)
{
printf("This value is %d\n",(TYPE64)(t));
//需要根据机器的位数选择int还是long
//不然编译的时候就会出现精度丢失的错误
}
int main()
{
int value = 5;
pthread_t t;
pthread_create(&t,NULL,func,(void *)value);
pthread_join(t,NULL);
return 0;
}