Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send additional parameters to an SDL Thread?

Yes, I know how to create an SDL thread.

int myfunc(void* data)
{
    //my code...
}
SDL_CreateThread* mythread=SDL_CreateThread(myfunc,NULL);

But what if i want to do something like:

int myfunc(void* data,int myparameter1,char myparameter2)
{
    //my code...
}
SDL_CreateThread* mythread=SDL_CreateThread(myfunc,NULL,42,'c');

i.e how to create a thread for a function with more than one parameters (parameters excluding the usual 'void* data') If this is not possible can you suggest any method by which i can pass a parameter to a thread?

like image 604
reubenjohn Avatar asked Feb 16 '23 20:02

reubenjohn


1 Answers

You can create a struct on the heap, set its fields with your data, then pass its address to SDL_CreateThread:

typedef struct {
    int param1;
    char param2;
} ThreadData;

int myfunc(void* data)
{
    ThreadData *tdata = data;
    int param1 = tdata->param1;
    char param2 = tdata->param2;
    free(data); // depending on the content of `data`, this may have
                // to be something more than a single `free`
    //my code...
}
ThreadData *data = malloc(sizeof(ThreadData));
data->param1 = ...;
data->param2 = ...;
SDL_CreateThread* mythread=SDL_CreateThread(myfunc,data);
like image 85
Tim Cooper Avatar answered Feb 18 '23 10:02

Tim Cooper