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?
This is a function pointer (or a pointer to a function).
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:
then you can pass it into the
CreateThreadfunction like so…So somewhere in
CreateThreadit will make a call:and your function DoSomeThing will be called and
void * datayou 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.