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);
}
4

1 回答 1

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
}
于 2012-11-01T20:41:49.407 回答