做瞹瞹网站,金华网站建设seo,国美网站建设的目的,单位的网站的建设方案条件变量通常与互斥锁一起使用#xff0c;用于线程间的同步。以下是条件变量常用的一些函数#xff1a;
①std::condition_variable::wait(lock, pred)#xff1a;线程调用此函数时#xff0c;会原子性地释放锁并阻塞当前线程#xff0c;等待另一个线程调用 notify_one 或…条件变量通常与互斥锁一起使用用于线程间的同步。以下是条件变量常用的一些函数
①std::condition_variable::wait(lock, pred)线程调用此函数时会原子性地释放锁并阻塞当前线程等待另一个线程调用 notify_one 或 notify_all 来通知。pred 是一个可选的谓词用于额外的条件检查如果传入 pred则当条件不满足时线程会继续等待。当被通知后wait 函数会重新获取锁。
②std::condition_variable::notify_one通知一个等待在条件变量上的线程使得其中一个线程被唤醒继续执行通常当对共享资源作出改变后调用该函数。
③std::condition_variable::notify_all通知所有等待在条件变量上的线程使得全部线程被唤醒继续执行。
这些函数通常会和互斥锁(std::mutex)一起使用例如
std::unique_lockstd::mutex lock(mtx);
cv.wait(lock, []{ return ready; }); // 等待 ready 变成 true
// 使用lambda表达式这里 cv 表示 std::condition_variablemtx 表示 std::mutexready 是一个共享的条件用于控制线程的同步。
举个见到的例子。
#include iostream
#include thread
#include mutex
#include condition_variable
#include queuestd::queueint q;
std::mutex mtx;
std::condition_variable cv;using namespace std;
void producer() {for (int i 0; i 10; i) {std::unique_lockstd::mutex lock(mtx);q.push(i);std::cout Producing i std::endl;lock.unlock();cv.notify_one(); // 通知消费者std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 为了方便观察加入延迟}
}void consumer() {for (int i 0; i 10; i) {std::unique_lockstd::mutex lock(mtx);cv.wait(lock, []{ return !q.empty(); }); // 等待直到队列不为空std::cout Consuming q.front() std::endl;q.pop();}
}int main() {std::thread producerThread(producer);std::thread consumerThread(consumer);producerThread.join();consumerThread.join();return 0;
}结果是
./a.out
Producing 0
Consuming 0
Producing 1
Consuming 1
Producing 2
Consuming 2
Producing 3
Consuming 3
Producing 4
Consuming 4
Producing 5
Consuming 5
Producing 6
Consuming 6
Producing 7
Consuming 7
Producing 8
Consuming 8
Producing 9
Consuming 9