1

我的任务是对打印服务器进行精简的多线程模型。

函数get_server的原型是:

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
4

2 回答 2

4

你是在正确的方式:

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函数的顶部(如果您正在调用pthread_createin main)。

于 2012-11-22T03:10:00.230 回答
0

您的函数需要一个指向 value的指针,但您传递的是value本身!因此,要遵循指针方案,您需要将指针传递给包含 value 的全局变量STDIN_FILENO

或者,您可以STDIN_FILENO像当前正在做的那样通过传递来“作弊”,然后将其void*转换为简单的int(不是指针!)并按原样使用它:

int fd = (int) arg;
于 2012-11-22T03:11:20.160 回答