【问题标题】:how to pass more than one argument in pthread_create() C programming Language [duplicate]如何在 pthread_create() C 编程语言中传递多个参数
【发布时间】:2021-07-11 17:33:32
【问题描述】:

我正在研究如何在 pthread_create() 中传递多个参数。初始化是

pthread_t th[1];
pthread_create(&th[i], NULL, &producer, shmData); 

我的生产者方法看起来像这样。

void producer(struct ShmData *shmData, sem_t *sem); 

当调用pthread_creat 时,我基本上需要同时传递shmDatasem。 我该如何完成这项任务?

【问题讨论】:

  • 您的线程函数应该采用一个指向某个数据结构的指针,该数据结构又将包含所有需要的参数。您的 producer 函数不适合按原样传递给 pthread_create
  • 你不能传递额外的参数。但是您可以使用一个void * 参数来指向包含您需要的数据的结构。确保在线程启动时结构仍然存在(并且没有被覆盖) - 例如,可能在创建函数中对其进行 malloc,并在使用后将其释放到线程中。

标签: c pthreads semaphore


【解决方案1】:

你需要为此使用结构

struct thread_arg {
   struct ShmData *shmData;
   sem_t *sem;
};

void producer(struct ShmData *shmData, sem_t *sem);

static void *producer_thread(void *p)
{
    struct thread_arg *arg = p;
    producer(p->shmData, p->sem);
    free(p);
    return NULL;
}

void fx()
{
    pthread_t th[1];
    struct thread_arg *arg = malloc(sizeof(*arg));
    arg->shmData = shmData; // from a variable something
    arg->sem = sem; // from a variable or something
    pthread_create(&th[i], NULL, producer_thread, arg);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2010-10-17
    相关资源
    最近更新 更多