如何从另一个函数内的随机位置调用C函数? [英] How to call a C function from random places inside another function?
问题描述
谁能告诉我如何在 C 函数内的随机位置插入函数调用(例如 Yield()
),当代码运行时, Yield()
从代码的不同部分被调用?
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 ?
我面临着我在合作线程环境中使用2个线程这样的要求,除非正在运行的线程显式地产生处理器,否则其他(正在等待)的线程将无法开始运行。我不想将 Yield()
调用放在单个点上,因为这会使线程序列具有确定性。在不重新布线整个环境(从协作到抢占)的情况下,这是我能想到的唯一解决方案,其中Thread_1()在随机位置进行 Yield()
调用
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!
推荐答案
我认为需要BFI解决方案
我认为您必须解决该问题明显的方法。您将需要为 Yield()
进行包装,从而对是否调用真实对象做出随机决定。
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.
如果您不关心执行速度,那么我会使其成为真正的C函数,如果您愿意,我建议使用预处理器宏。
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.
因此,
#define Yield0() ((random() & 0xf) == 0 && Yield())
为需要的通话机会选择百分比掩码。对于0xf,如果 random()
具有良好的低阶位随机性,则您将在16次调用中看到1 Yield()。如果可以使用MT或其他高质量的随机数生成器,则低阶位将直接有用,否则您可能需要 random()>> 3& ...
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 to random() >> 3 & ...
您只需要把Yield0()调用放在任何地方。
And you will just need to put Yield0() calls everywhere.
这篇关于如何从另一个函数内的随机位置调用C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!