在线程函数中使用String数组

时间:2012-11-01 20:24:20

标签: c pthreads signals

我正在尝试将数组传递给线程函数,以便它可以访问函数中的数组。目前它只包含线程的名称。

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

1 个答案:

答案 0 :(得分:0)

您可以尝试将线程ID与线程数据耦合:

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

在示例程序中,您可以创建一个函数,handler,并根据其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
}