是否可以将结构指针传递给函数的int参数



我正在学习Nachos操作系统,这是我课程的一部分。在修改操作系统的代码库时,我遇到了一个成员函数的以下注释,该成员函数允许您在新分叉的线程中运行函数(在这个操作系统中,进程被称为线程-不要问我为什么-请参阅官方文档(。我最感兴趣的是函数上方的文档字符串。我对评论的注释部分特别感兴趣。我不完全确定这里发生了什么。如何将一个结构传递给Fork函数,如果func应该通过一个结构使用多个参数,我们应该如何编写它?有人能解释一下吗?

//----------------------------------------------------------------------
// Thread::Fork
//  Invoke (*func)(arg), allowing caller and callee to execute 
//  concurrently.
//
//  NOTE: although our definition allows only a single integer argument
//  to be passed to the procedure, it is possible to pass multiple
//  arguments by making them fields of a structure, and passing a pointer
//  to the structure as "arg".
//
//  Implemented as the following steps:
//      1. Allocate a stack
//      2. Initialize the stack so that a call to SWITCH will
//      cause it to run the procedure
//      3. Put the thread on the ready queue
//  
//  "func" is the procedure to run concurrently.
//  "arg" is a single argument to be passed to the procedure.
//----------------------------------------------------------------------
typedef void (*VoidFunctionPtr)(int arg); 
void 
Thread::Fork(VoidFunctionPtr func, int arg)
{
// run the function 'func' in side the forked thread using the argument
// 'arg' as its input - look at VoidFunctionPtr type declaration above
}

我有一个问题与我在StackOverflow上的问题有关。我将把它链接到这里。但是,我不完全确定我是否理解。提前谢谢!

PS:完整的源代码链接在这里:code,thread.h,thread.cc

编辑:我知道使用标准库线程和其他标准库实现是非常安全和有用的,但作为课程的一部分,我不允许这样做。无论如何,我想了解这个代码库的作者想说什么。

我想了解这个代码库的作者想说什么。">

他们说,如果你想传递比int更多的数据,就把它放入你自己设计的结构中,比如说struct foo x,然后把(int) &x传递给Thread::Fork。他们指示你这样做的事实隐含着,Nachos操作系统只支持这样的转换保留指针的必要地址信息并支持将其转换回指向结构类型的指针的平台。

例如,您可以这样定义struct foo

struct foo
{
int a;
float b;
};

并以此方式定义func

void func(int arg)
{
struct foo *p = (struct foo *) arg;
printf("a is %d.n", p->a);
printf("b is %g.n", p->b);
}

最新更新