【问题标题】:pthread runs multiple timespthread 运行多次
【发布时间】:2015-11-17 15:58:14
【问题描述】:

我希望我的每个线程调用多个函数。我怎样才能做到这一点?现在我有只调用一个函数的线程代码:

pthread_attr_init(&attributes);
if((tid1 = pthread_create(&thread[0],&attributes,produce,NULL)))
{
    printf("\nError in the producer thread\n");
    printf("\n");
}

if((tid2 = pthread_create(&thread[1],&attributes,consume,NULL)))
{
    printf("\nERror in the consumer thread\n");
}

pthread_join(thread[0],NULL);
pthread_join(thread[1],NULL);

调用 pthread_create 会产生两个新线程吗?

【问题讨论】:

  • 你传递给pthread_create的函数就像main给你的程序:它的起点。然后,您可以将您想要的任何内容作为代码放入此函数中......您的问题是什么?
  • 我想我不明白的是如何在 pthread_create 中放置多个函数。
  • @ballballbobo 你能把一个函数放在另一个函数里面吗?

标签: c pthreads


【解决方案1】:

您不能将多个函数“传递”给pthread_create()。根本没有这方面的规定。但是,您可以在线程函数中调用任何您想要的函数,就像任何其他函数调用一样。

void *produce(void *arg)
{
   func1();
   func2();
   ...
}

void *consume(void *arg)
{
   funcx();
   funcy();
   ...
}

int main(void) 
{
...

if((tid1 = pthread_create(&thread[0],&attributes,produce,NULL)))
{
    printf("\nError in the producer thread\n");
    printf("\n");
}

if((tid2 = pthread_create(&thread[1],&attributes,consume,NULL)))
{
    printf("\nERror in the consumer thread\n");
}
...
}

或者,如果您想要将每个函数(例如示例中的 func1func2)单独的线程作为单独的线程,那么您只需对每个函数调用 pthread_create() 多次作为参数的函数(即线程函数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2020-07-24
    • 2013-01-15
    相关资源
    最近更新 更多