阅读量:120
在C++中,为了避免使用pause函数导致的资源浪费,您可以考虑以下替代方案:
- 使用条件变量(Condition Variable):条件变量是一种同步原语,允许线程等待某个条件成立。当条件满足时,线程将被唤醒。这样可以避免忙等待(busy waiting),从而减少资源浪费。
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_block() {
std::unique_lock lock(mtx) ;
while (!ready) {
cv.wait(lock); // 忙等待,但不会消耗CPU资源
}
std::cout << "Ready!" << std class="hljs-function">void set_ready() {
std::lock_guard lock(mtx) ;
ready = true;
cv.notify_one(); // 唤醒等待的线程
}
int main() {
std::thread t1(print_block);
std::thread t2(set_ready);
t1.join();
t2.join();
return 0;
}
- 使用事件(Event):事件是一种同步原语,允许线程等待某个事件发生。当事件发生时,线程将被唤醒。这样可以避免忙等待,从而减少资源浪费。
#include
#include
#include
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // 创建事件
void print_block() {
WaitForSingleObject(hEvent, INFINITE); // 等待事件发生
std::cout << "Ready!" << std class="hljs-function">void set_event() {
SetEvent(hEvent); // 设置事件,唤醒等待的线程
}
int main() {
std::thread t1(print_block);
std::thread t2(set_event);
t1.join();
t2.join();
CloseHandle(hEvent); // 关闭事件句柄
return 0;
}
这些替代方案可以有效地避免使用pause函数导致的资源浪费。