互斥锁(mutex)用于互斥访问临界区,只允许一个线程访问共享变量。
条件变量可以让获取互斥锁 的线程在某个条件变量上等待,直到有其他线程把他唤醒。

互斥锁和条件变量通常一起使用实现同步。

互斥锁的操作

lock(mutex); // 获取锁,如果获取不到锁,线程进入阻塞状态,释放CPU

unlock(mutex) ;//释放锁

try_lcok(mutex);//非阻塞 获取锁,如果获取不到,就返回错误码

条件变量的操作

condition_variable cond;

cond.wait(..);//在条件变量上等待,线程进入阻塞状态,直到有其他线程把它唤醒

cond.notify(..); //唤醒等待在cond的某个线程

cond.notifyall(..);//唤醒等待在cond的所有线程

使用互斥锁和条件变量解决消费者生成者问题

进程通信(7):互斥锁(mutex)和条件变量_操作系统

#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <condition_variable>
class Shared{
public:
    std::mutex mutex;
    std::condition_variable cond_var;
    std::vector<int> buffer;
    const int capacity;  //缓冲区容量
    Shared(int cap):capacity(cap){}   
    void produce(int value) {
        std::unique_lock<std::mutex> lock(mutex);
        while (buffer.size() == capacity) cond_var.wait(lock); 
        buffer.push_back(value);   std::cout << "Produced: " << value << "\n";
        cond_var.notify_all();// 通知所有等待的线程
    }
    int consume() {
        std::unique_lock<std::mutex> lock(mutex);
        while (buffer.empty()) {
            cond_var.wait(lock); // 缓冲区空时等待
        }
        int val = buffer.front();
        buffer.erase(buffer.begin());    std::cout << "Consumed: " << val << "\n";
        cond_var.notify_all(); // 通知所有等待的线程
        return val;
    }
};

Shared shared(10); // 缓冲区容量为10

void producer_function() {
    for (int i = 0; i < 20; ++i) {
        shared.produce(i);
    }
}

void consumer_function() {
    for (int i = 0; i < 20; ++i) {
        shared.consume();
    }
}

int main() {
    std::thread producer(producer_function);
    std::thread consumer(consumer_function);
    producer.join();
    consumer.join();
    return 0;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.