2012-05-20 160 views
-1

我傳遞隊列這樣的源文件AC和BC之間傳遞隊列作爲參數在C

文件:AC

sq[a]=new_queue(); 

pthread_create(&st[a],NULL,sendPacket,sq[a]); 

文件:BC

void *sendPacket(void *queue){ 

/* here i need to know which queue has come ,determine 
    the index of queue how can I do it? */ 
} 
+1

請更新您的稱號;問題不在於「將隊列作爲參數傳遞」。 –

回答

0

可能如果您只是將索引傳遞給函數,則更容易:

void *sendPacket(int queue_idx) { 
    queue_t *queue = &sq[queue_idx]; 
} 
1

創建隊列的更高級表示。看來隊列可以是一個void *(你沒有顯示出它的實際類型,即什麼是new_queue()調用返回?),所以嵌入在一個結構,而添加額外的參數:

struct queue_state { 
    void *queue; 
    int index; 
}; 

然後實例化結構和指針傳遞給它的線程函數:

struct queue_state qsa = malloc(sizeof *qsa); 
if(qsa != NULL) 
{ 
    qsa->queue = new_queue(); 
    qsa->index = 4711; /* or whatever */ 
    pthread_create(&st[a], NULL, sendPacket, qsa); 
} 

然後線程函數可以使用struct聲明訪問所有的領域。當然,這個聲明需要在一個共享頭文件中(比如說queue.h),它包含在這兩個C文件中。

0

如果在b.c您有權訪問sq,您可以將索引傳遞給隊列。否則,您可以傳遞包含實際隊列和索引的結構

1

您的問題描述非常粗糙。但至少從我的理解,你實際上需要傳遞2個參數到你的函數:(指向)隊列(這似乎是我的一個數組),以及這個隊列中的索引。

您不得將兩個參數都包含在void*類型的單個變量中。你可以做的是聲明一個包含所有必要參數的結構體,填充它並將指針傳遞給你的線程。

這樣的(處理忽略錯誤):

struct Params 
{ 
    queue* m_Queue; 
    size_t m_Idx; 
}; 

// ... 
Params* pParams = new Params; 
pParams->m_Queue = sq; 
pParams->m_Idx = a; 

pthread_create(&st[a],NULL,sendPacket, pParams); 


void *sendPacket(void *pPtr) 
{ 
    Params* pParams = (Params*) pPtr; 

    // ... 

    delete pParams; 
}