2012-11-01 18 views
0

我試圖將數組傳遞給線程函數,以便它可以訪問函數中的數組。目前它只包含線程的名稱。在線程函數中使用字符串數組

const char *a[2]; 
char *s = "Thread 1"; 
char *r = "Thread 2"; 
a[0] = s; 
a[1] = r; 
pthread_create(&t, NULL, oddhandler, (void *)a[0]); 
pthread_create(&y, NULL, evenhandler, (void *)a[1]); 

的目的是編寫創建這樣

pthread_create(&t, NULL, oddhandler, &a); 
pthread_create(&y, NULL, evenhandler, &a); 

我將如何重新寫這個功能,以適應這種變化?

static void * 
oddhandler(void *p) 
{ 
    char *q = (char *)p; 
    printf("%s is ready.\n", q); 
    sigset_t set; 
    int sig = SIGUSR1; 

    sigemptyset(&set); 

    sigaddset(&set, SIGUSR1); 

    while (1) { 

     /* Wait for SIGUSR1 */ 
     sigwait(&set, &sig); 

     printf("%s received a SIGUSR1!\n", q); 

    } 

    return ((void *)NULL); 
} 
+0

難道你的意圖是每個線程proc都會收到'a'的基地址,char指針數組? – WhozCraig

+0

所以你想創建的線程自動知道使用哪個索引來獲取他們的名字?即不是傳入名稱,而是傳遞數組a的開始,並且每個線程都知道索引a的數量是多少? – Joe

+0

不,這個想法是在打印語句中用[0]和[1]代替q。我只是使用線程名稱作爲示例。線程都將打印已放置在該數組中的字符串。 –

回答

0

你可以嘗試用數據線連接線程ID:

typedef struct thread_info { 
    int thread_id; // different for every thread 
    void * thread_data; // the same for every thread 
} 

在你的示例程序,您可以創建一個函數,處理程序,並具有線程調整基於其ID。

pthread_create(&(t[id], NULL, handler, &(info[i])); 

void * handler(void * info) { 
    thread_info * myInfo = (thread_info *) info; 
    char *q = ((char *) myInfo->thread_data) + myInfo->thread_id; 

    // rest of function 
}