我的任务是制作打印服务器的精简多线程模型。
函数get_server的原型(prototype)是:
void *get_request(void *arg);
“参数 arg 指向要从中读取请求的打开文件描述符。”因此在测试中建议使用 STDIN_FILENO,但总而言之,描述符需要是通用的。
pthread_create(&tid, &attr, get_request, STDIN_FILENO);
在我尝试使用 arg 的函数中,无法将它从 void * 更改为任何可用的值。例如,这些都不起作用:
read(*arg, intvariable, sizeof(int)); // can't cast void * error
int fd = *arg; // can't cast void * error
int fd = *(int *)arg; // seg fault
int fd = *((int *)arg); // seg fault
int fd = atoi(arg); // seg fault
// yes I'm aware arg isn't a char* but that's
// from the example code we were given
你走对了:
void *get_request(void *arg)
{
int fd = (int) arg;
...
}
但是,这不是推荐的方式。而是创建一个变量并将其地址传递给 pthread_create
调用:
int fd = STDIN_FILENO;
pthread_create(&tid, &attr, get_request, &fd);
然后你使用
void *get_request(void *arg)
{
int fd = *((int *) arg);
...
}
不过要小心,用于 pthread_create
调用的变量范围不会在线程启动之前用完。然后你将有一个指向未使用内存的指针。将此变量放在 main
函数的顶部(如果您在 main
中调用 pthread_create
)。
我是一名优秀的程序员,十分优秀!