如何只减慢一部分代码而不减慢其余部分?



我尝试过使用睡眠、延迟函数等。这些都减慢了整个代码的速度,如下所示。当只有 DoThis 为 True 时,它以所需的速度打印数字。当只有 DoThat 为真时,它也以所需的速度运行。但是,当两者都运行时,睡眠适用于整个程序,显然不是解决方案,只是我需要做的事情的示例。有没有办法减慢DoThis的输出而不是其余代码/允许其他代码同时运行?

我需要:
只慢 DoThis 输出
不要更改不可更改的值
同时运行 DoThis 和 DoThat 函数

int main() {
int True = 1;
int UnchangebleValue = 1;
int DoThis = 1;
int DoThat = 1;
while (DoThis >= True || DoThat <= True) {
if (DoThis >= True) {
DoThis += UnchangebleValue;
cout << DoThis << endl;
Sleep(1000); //Desired Effect, Needs to Apply Only Here
}
if (DoThat <= True) {
DoThat -= UnchangebleValue;
cout << DoThat << endl;
}   
}
return 0;
}

编辑:这是我想要使用线程建议完成的代码。如果有更好的方法可以做到这一点,我会全力以赴。感谢您的回复。

#include <thread>
#include <iostream>
int main() {
int True = 1;
int UnchangebleValue = 1;
int DoThis = 1;
int DoThat = 1;
std::thread t1([&DoThis, &DoThat, &UnchangebleValue, True]() {
while (DoThis >= True ) {   
DoThis += UnchangebleValue;
std::cout << DoThis << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
});
std::thread t2([&DoThis, &DoThat, &UnchangebleValue, True]() {
while (DoThat <= True) {
DoThat -= UnchangebleValue;
std::cout << DoThat << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
}       
});
t1.join();
t2.join();
return 0;
}

我真的无法理解你的总体目标或逻辑。

但是,如果您希望两段代码独立运行,则可以使用线程。从 C++11 开始,您可以使用 std::thread 以标准方式执行此操作。我更改了您的代码以使其在线程中运行(不了解目标(。我用了lambdas。

#include <thread>
#include <iostream>
int main() {
int True = 1;
int UnchangebleValue = 1;
int DoThis = 1;
int DoThat = 1;
std::thread t1([&DoThis, &DoThat, &UnchangebleValue, True]() {
while (DoThis >= True || DoThat <= True) {
if (DoThis >= True) {
DoThis += UnchangebleValue;
std::cout << DoThis << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}}
});
std::thread t2([&DoThis, &DoThat, &UnchangebleValue, True]() {
if (DoThat <= True) {
DoThat -= UnchangebleValue;
std::cout << DoThat << std::endl;
}});
t1.join();
t2.join();
return 0;
}

请注意,上面的代码中没有同步。在实际项目中,您需要原子值和/或互斥体(mutices(。

最新更新