如您所见,我想将函数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;
}
答案 0 :(得分:1)
简答:只需将参数作为第四个参数传递给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
正如您所看到的,它需要一个指向函数的指针,该函数需要void *
并返回void *
。幸运的是,这正是你所拥有的。并根据pthread_create
的手册页:
新线程通过调用
start_routine()
开始执行;arg
作为start_routine()
的唯一参数传递。