linux

C++ Linux编程中如何进行并发控制

小樊
33
2025-08-12 02:49:46
栏目: 编程语言

在C++ Linux编程中进行并发控制,主要涉及到多线程编程和同步机制。以下是一些常用的方法:

1. 多线程编程

使用C++11标准库中的<thread>头文件来创建和管理线程。

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread is running\n";
}

int main() {
    std::thread t(threadFunction);
    t.join(); // 等待线程完成
    return 0;
}

2. 同步机制

为了防止多个线程同时访问共享资源导致的数据竞争,需要使用同步机制。

2.1 互斥锁(Mutex)

使用std::mutex来保护共享资源。

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

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

void printMessage(const std::string& msg) {
    std::lock_guard<std::mutex> lock(mtx); // 自动加锁和解锁
    std::cout << msg << std::endl;
}

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

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

    return 0;
}

2.2 条件变量(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 workerThread() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return ready; }); // 等待条件变量

    std::cout << "Worker thread is processing data\n";
}

void trigger() {
    std::lock_guard<std::mutex> lock(mtx);
    ready = true;
    cv.notify_one(); // 通知一个等待的线程
}

int main() {
    std::thread worker(workerThread);
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟一些工作
    trigger();

    worker.join();
    return 0;
}

2.3 原子操作(Atomic Operations)

使用std::atomic来实现无锁编程。

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> counter(0);

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

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

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

    std::cout << "Counter value: " << counter.load() << std::endl;
    return 0;
}

3. 其他并发控制工具

示例:使用POSIX信号量

#include <iostream>
#include <thread>
#include <semaphore.h>

sem_t sem;

void workerThread() {
    sem_wait(&sem); // 等待信号量
    std::cout << "Worker thread is processing data\n";
}

void trigger() {
    sem_post(&sem); // 发送信号量
}

int main() {
    sem_init(&sem, 0, 0); // 初始化信号量,初始值为0

    std::thread worker(workerThread);
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟一些工作
    trigger();

    worker.join();
    sem_destroy(&sem); // 销毁信号量
    return 0;
}

通过这些方法,可以在C++ Linux编程中有效地进行并发控制,确保多线程程序的正确性和性能。

0
看了该问题的人还看了