簡體   English   中英

是否可以將結構指針傳遞給 function 的 int 參數?

[英]Is it possible to pass a struct pointer to an int argument of a function?

作為課程作業的一部分,我正在研究 Nachos 操作系統。 在修改操作系統的代碼庫時,我遇到了一個成員 function 的以下評論,它允許您在新分叉的線程中運行 function(在這個操作系統中,進程稱為線程 - 不要問我為什么 - 參考官方文檔)。 我最感興趣的是function上面的docstring。我對評論的NOTE部分特別感興趣。 我不完全確定這里發生了什么。 一個struct怎么傳遞給Fork function,如果要通過一個struct使用多個arguments我們應該怎么寫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:完整的源代碼鏈接在這里: codethread.hthread.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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM