[英]How can I sleep a function inside of a loop without using sleep()?
I'm trying to add a randomly generated number to a calculation but I don't want the randomly generated number to be randomly generated every 1ms (because that's how my try functions needs to run) and I can't use sleep() because it would sleep the entire process (my whole program).我正在尝试将随机生成的数字添加到计算中,但我不希望随机生成的数字每 1ms 随机生成一次(因为这就是我的 try 函数需要运行的方式)并且我不能使用 sleep() 因为它会休眠整个过程(我的整个程序)。
I've tried to sleep the randomnumbergenerator function every 1 second but the try do makes it run every 1ms, how can I sleep a function inside of a loop without using sleep()?我试图让随机数发生器 function 每 1 秒休眠一次,但尝试让它每 1ms 运行一次,我如何在不使用 sleep() 的情况下在循环内休眠 function?
Current code:当前代码:
int randomnumber = 0;
void randomnumbergenerator()
{
for (;;)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
int min = -1000;
int max = +2000;
int randomNum = rand() % max + (min);
randomnumber = randomNum;
}
}
try //this must run every 1 ms;
{
do
{
if (something)
{
std::thread(randomnumbergenerator).detach();
const int somenumber2 = something;
const int somenumber = something;
somenumber += somenumber2 * randomnumber ;
}
}
}
This is what worked for me:这对我有用:
uintptr_t milliseconds_now() {
static LARGE_INTEGER s_frequency;
static BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
if (s_use_qpc) {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (1000LL * now.QuadPart) / s_frequency.QuadPart;
}
else {
return GetTickCount64();
}
}
int randomrumber = 0;
void fn()
{
for (;;)
{
std::this_thread::sleep_for(std::chrono::seconds(4));
int min = -1000;
int max = +2000;
int randomNum = rand() % max + (min);
randomrumber = randomNum;
}
}
try //this must run every 1 ms;
{
do
{
if (something)
{
static std::uintptr_t desiredTime = 0;
if (milliseconds_now() >= desiredTime)
{
std::thread(fn).detach();
desiredTime = milliseconds_now() + 5000;
}
const int somenumber2 = something;
const int somenumber = something;
somenumber += somenumber2 * randomnumber ;
}
}
}
This solution isn't perfect tho.这个解决方案并不完美。 It makes my program lose some abilities.它使我的程序失去了一些能力。 Probably because it's not multithreaded.可能是因为它不是多线程的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.