2011-11-22 75 views
8

我想將兩個參數傳遞給C中的線程。我創建了一個數組(大小爲2),並試圖將該數組傳遞給線程。這是將多個參數傳遞給線程的正確方法嗎?如何將多個參數傳遞給C中的線程

// parameters of input. These are two random numbers 
int track_no = rand()%15; // getting the track number for the thread 
int number = rand()%20 + 1; // this represents the work that needs to be done 
int *parameters[2]; 
parameters[0]=track_no; 
parameters[1]=number; 

// the thread is created here 
pthread_t server_thread; 
int server_thread_status; 
//somehow pass two parameters into the thread 
server_thread_status = pthread_create(&server_thread, NULL, disk_access, parameters); 
+1

檢查你的代碼,您聲明指針數組爲int和分配他們與int值。 – Teudimundo

+0

我注意到了這個警告。如果參數不是指針而只是一個數組是否合法? –

+0

如果將參數聲明爲int(「int parameter [2];」)的數組,則可以將參數作爲指針傳遞。它是指向第一個int的指針。然後可以以線程的形式作爲數組訪問它。 – Teudimundo

回答

15

既然你在一個空指針傳遞,它可以指向任何東西,包括一個結構,按照以下例如:

typedef struct s_xyzzy { 
    int num; 
    char name[20]; 
    float secret; 
} xyzzy; 

xyzzy plugh; 
plugh.num = 42; 
strcpy (plugh.name, "paxdiablo"); 
plugh.secret = 3.141592653589; 

status = pthread_create (&server_thread, NULL, disk_access, &plugh); 
// pthread_join down here somewhere to ensure plugh 
// stay in scope while server_thread is using it. 
+3

當然,在如上例所示的代碼中,您必須確保在線程嘗試取消引用給定參數時不會破壞結構。 –

+0

最簡單的解決方法是'malloc'結構並使新線程負責釋放它。另一種方法是在結構中放置屏障,並在原始線程返回之前使原始線程和新線程都在屏障上等待。 –

+0

@FrerichRaabe也許一個愚蠢的問題,但結構如何「被銷燬」......除了調用'free()'(如果它是'malloc'ed)或函數返回(如果它被分配在堆棧),還有其他方法嗎? – The111

1

這是一種方法。另一個通常的方法是將指針傳遞給struct。這樣你可以有不同的「參數」類型,並且參數被命名而不是索引,這可以使代碼有時易於閱讀/遵循。