正确的线程传参:
#include <pthread.h> #include <errno.h> #include <stdio.h> void* say_hello(void* fd) { //对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取; int connectfd =*((int *)fd); printf("thread connectfd:%d\n",connectfd); pthread_exit(NULL); } int main() { pthread_t thread_recv; int i = -3; int ret = pthread_create(&thread_recv, NULL, say_hello, (void *)&i);//传入的时候必须强制转换为void* 类型,即无类型指针 printf("current pthread id = %d\n",thread_recv); if (ret != 0) { printf("pthread_create error: error_code=%d",ret); } ret = pthread_join(thread_recv,NULL); if(ret) { perror ("pthread_join join error:"); return ret; } while(1); }
优化代码这样写时,线程的传参是错误的,不知道问题出在哪了。
#include <pthread.h> #include <errno.h> #include <stdio.h> pthread_t thread_recv; void* say_hello(void* fd) { //对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取; int connectfd =*((int *)fd); printf("thread connectfd:%d\n",connectfd); pthread_exit(NULL); } void thread_init(int val) { int ret = pthread_create(&thread_recv, NULL, say_hello, (void *)&val);//传入的时候必须强制转换为void* 类型,即无类型指针 printf("current pthread id = %d\n",thread_recv); if (ret != 0) { printf("pthread_create error: error_code=%d",ret); } } int main() { int ret = -1; int i = -3; thread_init(i); ret = pthread_join(thread_recv,NULL); if(ret) { perror ("pthread_join join error:"); return ret; } while(1); }