pthread 中函数的参数数量 [英] number of arguments for a function in pthread

查看:59
本文介绍了pthread 中函数的参数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 pthread 的 hello world 示例中说明:

In hello world example of pthread it is stated:

#include <pthread.h>
#include <stdio.h>

void * print_hello(void *arg)
{
  printf("Hello world!\n");
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t thr;
  if(pthread_create(&thr, NULL, &print_hello, NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }

  if(pthread_join(thr, NULL))
  {
    printf("Could not join thread\n");
    return -1;
  }
  return 0;
}

正如你看到的 pthread_create() 中的 print_hello 没有参数,但是在定义中,它看起来像 void * print_hello(void *arg)

As you can see print_hello in pthread_create() has no argument, however in the definition, it looks like void * print_hello(void *arg)

这是什么意思?

现在假设我有这个实现

void * print_hello(int a, void *);
int main(int argc, char **argv)
{
  pthread_t thr;
  int a = 10;
  if(pthread_create(&thr, NULL, &print_hello(a), NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }
  ....
  return 0;
}
void * print_hello(int a, void *arg)
{
  printf("Hello world and %d!\n", a);
  return NULL;
}

现在我收到此错误:

too few arguments to function print_hello

那我该如何解决?

推荐答案

pthread 传递一个 void * 类型的参数给线程函数,所以你可以传递一个指针到您想要作为 pthread_create 函数的第四个参数的任何类型的数据,请查看下面修复您的代码的示例.

pthread passes one argument of type void * to thread function, So you can pass a pointer to any type of data that you want as fourth argument of pthread_create function, look at the example below that fixes your code.

void * print_hello(void *);
int main(int argc, char **argv)
{
    pthread_t thr;
    int a = 10;
    if(pthread_create(&thr, NULL, &print_hello, (void *)&a))
    {
        printf("Could not create thread\n");
        return -1;
    }
    ....
    return 0;
}

void * print_hello(void *arg)
{
    int a = (int)*arg;
    printf("Hello world and %d!\n", a);
    return NULL;
}

这篇关于pthread 中函数的参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆