c - What does int type convert to void* mean in pthread_create()? -
what such code mean:
int main() { typedef int udtsocket; udtsocket recver; pthread_create(&rsvthread, null, recvandsend, (void *)(unsigned long)recver); return 0; } void* recvandsend(void* usocket) { udtsocket recver = (udtsocket)(unsigned long)usocket; } such code right? (void *)(unsigned long)recver) mean, how can unsigned int convert void*, , how can void* convert udtsocket in
udtsocket recver = (udtsocket)(unsigned long)usocket; i think should be
pthread_create(&rsvthread, null, recvandsend, (void *)((unsigned long*)&recver)); and
void* recvandsend(void* usocket) { udtsocket recver = (udtsocket)(unsigned long)(*usocket); } someone can explain it?
the first approach pass value, second pass reference.
note: way how data passed thread function has essential impact on how variable can used after call pthread_create() had returned.
when passing value variable's value copied stack during call pthread_create(), has effect, original variable used again after calls return.
if passed reference value pointed reference isn't copied immediately, @ later point in time, typically after pthread_create() had returned. dues asynchronous nature of way thread's function (as passed pthread_create()) started, variable which's address had been passed in not reused immediately. if shall reused, access needs synchronised.
the first approach makes use of fact on platforms size of integer less or equal size of pointer.
this might work or not.
if going way, make sure use integer type guaranteed of same size pointer. intptr_t signed , uintptr_t unsigned integers.
to pass in data:
#include <stdint.h> /* intptr_t */ ... pthread_create(&rsvthread, null, recvandsend, (void *)((intptr_t) recver)); to pull out data:
void * recvandsend(void * pvsocket) { udtsocket recver = (udtsocket) ((intptr_t) pvsocket); ... the second approach portable way go, assuming doing c, following
to pass in data:
pthread_create(&rsvthread, null, recvandsend, &recver); to pull out data:
void * recvandsend(void * pvsocket) { udtsocket recver = *((udtsocket *) pvsocket); /* first cast pointer udtsocket, dereference pointer read out ispointing to. */ ...
Comments
Post a Comment