linux

C++如何实现Linux下的并发控制

小樊
49
2025-07-28 06:24:57
栏目: 编程语言

在Linux下,C++可以通过多种方式实现并发控制,主要包括多线程、互斥锁、条件变量、信号量等。以下是一些基本的实现方法:

  1. 多线程:使用C++11标准库中的<thread>头文件可以创建和管理线程。
#include <iostream>
#include <thread>

void helloFunction() {
    std::cout << "Hello from a thread!" << std::endl;
}

int main() {
    std::thread t(helloFunction);
    t.join(); // 等待线程完成
    return 0;
}
  1. 互斥锁:使用<mutex>头文件中的std::mutex类可以实现线程间的互斥访问。
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // 创建一个互斥锁

void printMessage(const std::string& msg) {
    mtx.lock(); // 加锁
    std::cout << msg << std::endl;
    mtx.unlock(); // 解锁
}

int main() {
    std::thread t1(printMessage, "Hello from thread 1");
    std::thread t2(printMessage, "Hello from thread 2");

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

    return 0;
}
  1. 条件变量:使用<condition_variable>头文件中的std::condition_variable类可以实现线程间的同步。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

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

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

void go() {
    std::lock_guard<std::mutex> 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(printId, i);

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

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

    return 0;
}
  1. 信号量:使用<semaphore>头文件(C++20引入)中的std::counting_semaphorestd::binary_semaphore类可以实现更高级的并发控制。
#include <iostream>
#include <thread>
#include <semaphore>

std::binary_semaphore sem(0); // 创建一个二进制信号量

void printMessage(const std::string& msg) {
    sem.acquire(); // 等待信号量
    std::cout << msg << std::endl;
}

int main() {
    std::thread t(printMessage, "Hello from a thread!");
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟一些工作
    sem.release(); // 发送信号量
    t.join();

    return 0;
}

这些是C++在Linux下实现并发控制的一些基本方法。在实际应用中,可能需要结合使用这些方法来实现更复杂的并发逻辑。此外,还可以使用其他同步原语,如读写锁、屏障等,以满足不同的并发需求。

0
看了该问题的人还看了