简体   繁体   English

将多个指针作为参数传递给pthread_create

[英]Pass multiple pointers as arguments to pthread_create

I am writing a tiny library for my game-server. 我正在为我的游戏服务器编写一个很小的库。 I wrote wrappers for pthread functions and would like to know if it's possible to pass multiple pointers to a function as a raw-byte array. 我为pthread函数编写了包装器,想知道是否可以将多个指针作为原始字节数组传递给函数。

typedef Thread pthread_t;
typedef int (ThreadFunction)(void *);

void* ThreadStarter(void* arg) {
    // This should get the passed Function, Argument and Detach from arg.

    Function(Argument) // Use the values passed.
    if (Detach)
        DoSomething();

    pthread_exit(0);

}

Thread StartThread(ThreadFunction* Function, void* Argument, bool Detach) {
    arg; // This is what I dont know how to do!

    pthread_t t;
    int errCode = pthread_create(&t, ThreadStarter, arg);
    if (errCode) {
        Log(ERROR, "StartThread: Cannot spawn thread. Failcode %d.", errCode);
        return;
    } else if (Detach)
        pthread_detach();

    return t;
}

I need a way to pass 3 pointers packed inside arg . 我需要一种方法来传递arg包装的3个指针。 I was thinking as a raw-byte array, but I feel it's not the way of doing it. 我当时想作为一个原始字节数组,但是我感觉这不是这样做的方法。 Using a struct to store these parameters is not allowed because of internal convention, so that's out-of-topic. 由于内部约定,不允许使用结构来存储这些参数,所以这是不合时宜的。

If a struct is not allowed, an array seems the only thing that remains. 如果不允许使用结构,则数组似乎仅存。 It must not be a local variable, though, because it's not guaranteed that ThreadStarter will stop using the argument before StartThread returns (those things happen unsychronized in parallel). 但是,它一定不能是局部变量,因为不能保证ThreadStarterStartThread返回之前会停止使用该参数(这些事情在并行运行时不同步)。 So you will need to put the arguments on the heap like 因此,您需要将参数放在堆上,例如

void **arg = (void**)malloc(sizeof(void*)*3));
arg[0] = ...;
...
arg[2] = ...;
pthread_create(&t, ThreadStarter, arg)

and then free() the received pointer in ThreadStarter (and when pthread_create fails), ie 然后在ThreadStarter (以及当pthread_create失败时) free()接收到的指针,即

void* ThreadStarter(void* arg_) {
  void **arg = (void**)arg_;
  // Use arg[0], arg[1], arg[2]
  free(arg);
  [...]
}

You will probably have to allocate a structure (or an array if all the informations have the same type), place the relevant informations in its members, and create the thread with the allocated structure (pointer) as only argument. 您可能必须分配一个结构(如果所有信息都具有相同的类型,则可以分配一个数组),将相关信息放入其成员中,并使用分配的结构(指针)作为唯一参数来创建线程。
Then the thread has to free this structure once the informations in its members have been retrieved. 然后,一旦检索到其成员中的信息,线程就必须释放此结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM