如何通过void函数中的命令行参数传递多个值?

时间:2017-01-15 10:06:31

标签: c pthreads command-line-arguments

#define SMALL_STACK 131072 //128K for stack
pthread_attr_t thread_attr; //for attr

void* fn(void* arg)
{ //fn fuction
  printf("%d", (char *) arg);
  return NULL;
}

int main(int argc, char** argv)
{
  printf("Have ");
  printf(" arguments:"); //checking multiple arguments
  for (int i = 0; i < argc; ++i)
  {
    printf("%s", argv[i]);
  }
  printf("\n");
  pthread_attr_init(&thread_attr);
  pthread_attr_setstacksize(&thread_attr, SMALL_STACK);
  pthread_t th; //creating thread and stack

  /* I Need Help (void*)&argv[1] passing this to void *fn function printing the argument coming from command line arguments */

  pthread_create(&th, &thread_attr, fn, (void*) &argv[1]); //creating thread

  return 0;

}

2 个答案:

答案 0 :(得分:0)

在我看来,您应该将struct实例传递给您的线程参数。

下面是一个例子:

struct MyThreadData
{
    int argc,
    char** argv;
}

void* fn(void* arg)
{
    MyThreadData* data=(MyThreadData*)arg;
    /*code*/
    return NULL;
}

int main(int argc, char** argv)
{
    /*...*/
    MyThreadData td={0};
    td.argc=argc;
    td.argv=argv;

    void* ret = NULL;
    pthread_create(&th, &thread_attr, fn, (void*)&td);
    pthread_join(th,&ret)
}

答案 1 :(得分:0)

传递一个参数(此处:第一个)更改

pthread_create(&th, &thread_attr, fn, (void*)&argv[1]); 

pthread_create(&th, &thread_attr, fn, argv[1]);

要在线程函数内打印字符串,请使用正确的转换说明符:

printf("%s", (char *)arg);

或以“更清洁”的方式做

void* fn(void* arg)
{
  char * pc = arg;
  printf("%s\n", pc); /* add a new-line to flush stdout, to 
                         have this printed immediately. */

要传递所有参数,请更改

pthread_create(&th, &thread_attr, fn, (void*)&argv[1]); 

pthread_create(&th, &thread_attr, fn, argv);

并按如下方式调整线程功能:

void* fn(void* arg)
{
  char ** ppc = arg;

  while (*ppc)
  {
    printf("%s\n", *ppc);
    ++ppc;
  }

  ...

同时确保main()不返回标准方式,因为这会结束进程,进而结束进程的所有线程。

为此,请替换

return 0;

通过

pthread_exit(NULL);