这个错误通常是因为在使用条件变量之前没有正确包含相应的头文件。在C++中,条件变量位于
头文件中,而互斥量位于
头文件中。因此,为了解决这个问题,您需要确保在使用条件变量之前正确包含这两个头文件。
下面是一个示例代码,展示了如何使用条件变量和互斥量,并避免出现此错误:
#include
#include
#include
#include
std::mutex mtx; // 定义互斥量
std::condition_variable cv; // 定义条件变量
bool ready = false; // 全局变量,用于标识是否准备好
void workerThread()
{
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
std::unique_lock lock(mtx); // 加锁
ready = true; // 设置准备好的标志
cv.notify_one(); // 通知等待的线程
}
int main()
{
std::cout << "Main thread starts." << std::endl;
std::thread t(workerThread); // 创建工作线程
std::unique_lock lock(mtx); // 加锁
cv.wait(lock, []{ return ready; }); // 等待条件变量满足
std::cout << "Main thread resumes." << std::endl;
t.join(); // 等待工作线程结束
std::cout << "Main thread exits." << std::endl;
return 0;
}
在这个示例中,通过包含
和
头文件,正确定义了条件变量和互斥量。通过使用std::unique_lock
定义一个独占的互斥锁,可以确保在线程等待和唤醒时正确加锁和解锁互斥量。
请确保在编译时使用g++
命令,并指定正确的头文件路径和编译选项。例如,使用以下命令编译示例代码:
g++ -std=c++11 example.cpp -o example -lpthread
这将使用C++11标准编译示例代码,并链接pthread
库以支持多线程操作。