简体   繁体   中英

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.

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 . 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). 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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