117.info
人生若只如初见

Linux下C++多线程同步怎么做

在Linux下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的线程同步机制:

1. 互斥锁(Mutex)

互斥锁是最基本的同步机制,用于保护共享资源,防止多个线程同时访问。

#include 
#include 
#include 

std::mutex mtx; // 全局互斥锁

void print_block(int n, char c) {
    mtx.lock(); // 加锁
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
    mtx.unlock(); // 解锁
}

int main() {
    std::thread th1(print_block, 50, '*');
    std::thread th2(print_block, 50, '$');

    th1.join();
    th2.join();

    return 0;
}

2. 条件变量(Condition Variable)

条件变量用于线程间的等待和通知机制。

#include 
#include 
#include 
#include 

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id(int id) {
    std::unique_lock lck(mtx);
    cv.wait(lck, []{return ready;}); // 等待条件变量
    std::cout << "Thread " << id << '\n';
}

void go() {
    std::lock_guard lck(mtx);
    ready = true;
    cv.notify_all(); // 通知所有等待的线程
}

int main() {
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(print_id, i);

    std::cout << "10 threads ready to race...\n";
    go(); // go!

    for (auto &th : threads) th.join();

    return 0;
}

3. 信号量(Semaphore)

信号量是一种更高级的同步机制,可以用于控制对共享资源的访问。

#include 
#include 
#include 

std::binary_semaphore sem(0); // 二进制信号量

void print_block(int n, char c) {
    sem.acquire(); // 等待信号量
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
}

void go() {
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟一些工作
    sem.release(); // 释放信号量
}

int main() {
    std::thread th1(print_block, 50, '*');
    std::thread th2(print_block, 50, '$');

    std::thread t(go);

    th1.join();
    th2.join();
    t.join();

    return 0;
}

4. 原子操作(Atomic Operations)

原子操作可以在不使用锁的情况下实现线程安全的操作。

#include 
#include 
#include 

std::atomic counter(0);

void increment() {
    for (int i = 0; i < 100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

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

    t1.join();
    t2.join();

    std::cout << "Counter: " << counter.load() << '\n';

    return 0;
}

5. 屏障(Barrier)

屏障用于确保多个线程在某个点上同步。

#include 
#include 
#include 

std::barrier bar(2); // 创建一个屏障,等待两个线程

void print_hello() {
    std::cout << "Hello from thread " << std::this_thread::get_id() << '\n';
    bar.arrive_and_wait(); // 等待其他线程
    std::cout << "After barrier from thread " << std::this_thread::get_id() << '\n';
}

int main() {
    std::thread t1(print_hello);
    std::thread t2(print_hello);

    t1.join();
    t2.join();

    return 0;
}

这些是Linux下C++多线程编程中常用的同步机制。根据具体的需求和场景,可以选择合适的同步机制来实现线程间的协调和通信。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe87fAzsKAg9QAl0.html

推荐文章

  • GitLab Linux版权限如何管理

    在Linux上管理GitLab的权限,通常涉及以下几个步骤: 安装GitLab:首先,需要在Linux系统上安装GitLab。这可以通过包管理器(如apt或yum)来完成。例如,对于Deb...

  • Linux中GitLab如何升级

    在Linux系统中升级GitLab通常涉及以下步骤:
    准备工作 备份数据:在进行任何升级操作之前,务必备份GitLab的所有数据,包括数据库、配置文件和重要的项目数...

  • GitLab Linux版如何备份

    在Linux上备份GitLab实例是一个重要的任务,以确保数据的安全性和可恢复性。以下是备份GitLab Linux版的详细步骤:
    全备份 集成包安装:
    sudo gitlab-...

  • Linux GitLab安全设置怎么做

    在Linux上设置GitLab的安全性是一个复杂但至关重要的过程。以下是一些关键的安全措施和建议,帮助你构建一个安全的GitLab环境:
    基本安全配置 配置防火墙:...

  • C++在Linux中如何使用智能指针

    在C++中,智能指针是一种对象,它模拟了指针的行为,但提供了额外的功能,如自动内存管理。在Linux环境下,你可以使用C++标准库中的智能指针来避免内存泄漏和其他...

  • Linux环境中C++代码如何优化

    在Linux环境中优化C++代码可以从多个方面入手,包括代码风格、构建与调试、编译器优化、算法优化、内存管理等。以下是一些具体的优化技巧:
    代码风格与文档...

  • Linux中C++项目如何构建和管理

    在Linux环境下构建和管理C++项目涉及多个步骤,包括环境准备、编写代码、编译、链接、调试、优化以及使用构建工具等。以下是详细的流程和工具介绍:
    环境准...

  • C++在Linux中如何使用正则表达式

    在 Linux 中,C++ 使用 库来处理正则表达式。 库是在 C++11 中引入的,因此需要确保编译器支持 C++11 或更高版本。
    下面是一个简单的示例,演示了如何在 C+...