c++ - Why do we pass function arguments as void* in pthread_create? -


i have started operating system course. ask might childish question never mind. learning multi-threading. here question: whenever create thread using pthread_create(), why need pass arguments of function want our thread run in type void*?

for example, consider following code.

void *test(void* data) {    ... }  int main() {       int temp;       pthread_t tid;       pthread_attr_t attr;        pthread_attr_init(&attr);       pthread_create(&tid, &attr, test, (void*)&temp); } 

so, here in,

pthread_create(&tid, &attr, test, (void*)&temp); 

why need type cast integer void*. why not pass integer is? , similarly, instead of

void* test(void* data); 

why not this,

void* test(int data); 

first off, pthread_create() c function, not c++, things c++ could @ point -- e.g. using templates -- not possible. c programs want start threads well.

(actually newer versions of c++ have own threading interface.)

so, c.

the idea have generic interface, can pass anything any function called pthread_create(), , return well.

you can't pass-by-value, because don't know size of argument. int, double, or struct something? need pass pointer.

and since don't know type of argument (and return value) either, use void *, "anonymous" pointer type. inside called thread function (test() in case), do know type of argument , return value, can cast , void * appropriate.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -