Can anyone tell me how to insert a function call (say Yield() ) at random places inside a C function, so that each time the code is run, Yield() gets called from different parts of the code ?
I am faced with such a requirement as I’m using 2 threads in a cooperative threading environment , where unless the running thread yields the processor explicitly , the other (waiting) thread cannot start running. I don’t want to place the Yield() call at a single point , since that makes the thread sequence deterministic. Without rewiring the entire environment (from cooperative to pre-emptive) , this is the only solution I can think of in which Thread_1() makes the Yield() call at random places inside it, allowing Thread_2() to take over.
Any insights into a different solution achieving the same end-goals is also welcome!
A BFI solution is called for, I think
I think you will have to solve this the obvious way. You will need to make a wrapper for
Yield()that makes a “random” decision on whether to call the real thing.If you are not concerned with execution speed then I would make it a real C function, and if you are I might suggest a preprocessor macro.
So, something like:
Choose the mask for the percentage chance of a call you want. For 0xf, and if
random()has good low-order bit randomness, then you would see 1 Yield() in 16 calls. If you can use an MT or other high quality random number generator, the low order bits will be directly useful, otherwise you might want torandom() >> 3 & ...And you will just need to put Yield0() calls everywhere.