Kinda Stupid Problem with threads

nobody wrote on Wednesday, June 23, 2004:

this may seem like a kindof stupid problem with threads…
but can anyone show me a little code example on how to pass an int to the function being called by glfwCreateThread()?

marcus256 wrote on Wednesday, July 07, 2004:

You can either do it the ugly way, and cast an int to void*:

  int myint = 312341;

…and the thread does the opposite:

void GLFWCALL mythreadfun(void *arg)
  int myint = (int)arg;

Since casting between ints and pointers is usually a BAD IDEA(TM), the better/nicer solution is to use an integer that is guaranteed to live during the entire lifetime of the thread (i.e. NOT a local variable), and pass a pointer to that int as the argument.

You have to figure out how to manage this longlived int yourself, as it has to do with what you want to do with your thread.

The typical solution would be to allocate memory for a struct that holds all the info/state necessary for the thread, fill it out, and send a pointer to the struct as the argument to the thread. Don’t forget to free the memory once the thread is done (do this after glfwWaitThread):

  struct a_struct_type * mystruct;
  mystryct = (struct a_struct_type *) malloc(sizeof(struct a_struct_type));
  mystruct->this = 23;
  mystruct->that = 130598;
  ID = glfwCreateThread(mythreadfun,mystruct);

void GLFWCALL mythreadfun(void *arg)
  struct a_struct_type * mystruct = arg;
  do_something_with( mystruct->this );

…or something similar, untested, out of my head.

nobody wrote on Friday, September 10, 2004:

thanks… heaps