【问题标题】:Stuck on a thread issue卡在线程问题上
【发布时间】:2013-05-08 13:46:21
【问题描述】:

所以我有这个

void* tf(void* p);

我完全不明白。我认为它是一个函数指针,带有一个用于参数的 void 指针。我正在使用它来制作这样的线程:

pthread_create( &thread_id[i], NULL, tf, NULL );

我需要的是对 tf 的解释以及如何将参数传递给它。

我将函数定义为

void* tf(void* p) 
{
    //I would like to use p here but dont know how. 
}

这个函数在 main 之外,需要获取一些在 main 内部设置的其他参数。我试着让它看起来像这样 tf(int i) 但我得到一个段错误。所以我知道我做错了什么,需要一些帮助来解决。

感谢您在这方面的任何帮助。

杰森

【问题讨论】:

标签: c multithreading function-pointers


【解决方案1】:
pthread_create( &thread_id[i], NULL, tf, NULL );
//                                      ^^^^^
//                       You have to put here the pointer (address) to your data

然后你可以从p指针中获取你的数据到线程函数中

例子

typedef struct test {
   int a,b;
} test;

int main() 
{
   struct test T = {0};
   pthread_create( &thread_id[i], NULL, tf, &T );
   pthread_join(thread_id[i], NULL); // waiting the thread finish
   printf("%d  %d\n",T.a, T.b);
}

void* tf(void* p) 
{
    struct test *t =  (struct test *) p;
    t->a = 5;
    t->b = 4;
}

【讨论】:

    【解决方案2】:

    pthread_create 的最后一个参数被传递给线程函数。

    因此,在您的情况下,将要传递给线程函数的内容定义为在线程创建函数中传递其地址。喜欢

    //in main
    char *s = strdup("Some string");
    pthread_create( &thread_id[i], NULL, tf, s );
    ...
    
    void* tf(void* p) 
    {
        char *s = (char *) p;
        // now you can access s here.
    
    }
    

    【讨论】:

      【解决方案3】:

      回调函数的 void 参数可以是一个指针,指向你想要的任何东西或什么都没有(NULL)。你只需要正确地投射它。 tf 函数本身是预期执行子线程工作的函数,如果您希望它在退出时返回某种值,那么您将其作为指针返回,就像您通过时所做的一样启动线程的参数。

      struct settings
      {
          int i;
          int j;
          char* str;
      };
      
      void* tf( void* args )
      {
          int result = 0;
      
          struct settings* st = (struct settings*)args;
      
          // do the thread work...
      
          return &result;
      }
      
      int main( int argc, char** argv )
      {
          struct settings st;
      
          st.i = atoi( argv[1] );
          st.j = atoi( argv[2] );
          st.str = argv[3];
      
          pthread_create( &thread_id[i], NULL, tf, &st );
      
          // do main work...
      }
      

      【讨论】:

        【解决方案4】:

        tf 只是一个接收void * 参数并在最后返回void * 值的函数。目前还没有函数指针。

        pthread_create 需要一个指向函数的指针才能执行,因此您需要通过&tf 来传递tf 的位置,而不是传递tf

        void * 在 C 中只是一个完全通用的指针。所以你把它投射到你传入的任何东西上,因此:

        int a = 4;
        void * a_genptr = (void *)&a;
        pthread_create(... &tf ... a_genptr ...);
        
        void * tf(void * arg) {
            int thatIntIWanted = *(int *)arg; // cast void * to int *, and dereference
        }
        

        你可以在this other SO question看到一个例子

        【讨论】:

        • 感谢您的解释。这些肯定会帮助我解决问题。有时间我会试试这个。
        猜你喜欢
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多