I've come across this piece of code
inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
I don't understand this part
void(*pfn)(void*)
Can someone tell me what it means/is?
This is btw not listed in books for beginners so if you want to mention to read books, it's not there.
Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?
It's a function pointer to a function returning void
and accepting void *
.
void example(void *arg);
You can find more information about function pointers in C++ (and in C) at The Function Pointer Tutorials.
This is a function pointer (or a pointer to a function).
void(*pfn)(void*)
This is broken down as such:
*pfn
(the name of the pointer i.e. pointer to a function)
(void *)
(these are the parameters to the function ie. a simple pointer to anything)
void
(this is return from the function)
So if you have a function like this:
void DoSomeThing(void *data) {
... does something....
}
then you can pass it into the CreateThread
function like so...
int i = 99;
void * arg = (void*)&i;
pthread_t thread = CreateThread(DoSomeThing, arg, ... other parameters ...);
So somewhere in CreateThread
it will make a call:
pfn(parg);
and your function DoSomeThing will be called and void * data
you get will be the arg you passed in.
More info:
Remember that code is just a sequence of bytes in memory. It's just how the cpu interprets them that makes them different from the thing we call data.
So at any point in a program we can refer to another part of the code by it's memory address. Since the code is broken down into functions with in C, this is a useful unit of reuse that C understands and allows us to treat the address of the function as just another pointer to some data.
In the above example the CreateThread function needs the address of a function so it can execute that function in a new thread. So we pass it a pointer to that function. Hence we pass it a function pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With