使用 C++11 中的 mutex 类来实现线程锁

188 阅读1分钟
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // 定义一个互斥锁

void print_num(int num) {
    // 上锁
    mtx.lock();

    // 输出数字
    std::cout << "Number: " << num << std::endl;

    // 解锁
    mtx.unlock();
}

int main() {
    std::thread t1(print_num, 1);
    std::thread t2(print_num, 2);
    std::thread t3(print_num, 3);

    // 等待线程结束
    t1.join();
    t2.join();
    t3.join();

    return 0;
}

在 C++ 中,可以使用 std::mutex 类来实现线程锁。下面是一个简单的线程锁示例,它使用了 std::lock_guard 来保护临界区:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mutex;
int counter = 0;

void increment()
{
    // 使用 std::lock_guard 来保护临界区
    std::lock_guard<std::mutex> lock(mutex);
    counter++;
}

int main()
{
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();

    std::cout << "Counter: " << counter << std::endl;

    return 0;
}