How to send additional parameters to an SDL Thread?

▼魔方 西西 提交于 2019-12-10 16:49:46

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17792542/how-to-send-additional-parameters-to-an-sdl-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!