如您所见,我想将函数传递send_message
给pthread_create
,但是我不知道如何传递其参数。怎么做?
pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message?
void *send_message(void *sockfd){
char buf[MAXLEN];
int *fd = (int *)sockfd;
fgets(buf, sizeof buf, stdin);
if(send(*fd, buf, sizeof buf, 0) == -1){
printf("cannot send message to socket %i\n", *fd);
return (void *)1;
}
return NULL;
}
简短的答案:只需将参数作为第四个参数传递给pthread_create
。
更长的答案:(pthread_create
按手册页)定义如下:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
第三个参数的含义可以通过以下方式解码cdecl
:
cdecl> explain void *(*start_routine) (void *)
declare start_routine as pointer to function (pointer to void) returning pointer to void
如您所见,它需要一个指向avoid *
并返回a的函数的指针void *
。幸运的是,这正是您所拥有的。并根据手册页pthread_create
:
新线程通过调用开始执行
start_routine()
;arg
作为的唯一参数传递start_routine()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句