商城首页欢迎来到中国正版软件门户

您的位置:首页 >Ubuntu C++如何实现并发控制

Ubuntu C++如何实现并发控制

  发布于2026-04-20 阅读(0)

扫一扫,手机访问

在Ubuntu上使用C++实现并发控制

想在Ubuntu环境下用C++玩转并发编程?这事儿说复杂也复杂,说简单也简单。自从C++11把标准线程库()纳入麾下,多线程开发的门槛就大大降低了,安全性和便捷性也上了一个台阶。今天,咱们就来聊聊几个核心的并发控制概念,并看看如何在Ubuntu上用C++把它们实现出来。

Ubuntu C++如何实现并发控制

1. 创建线程

万事开头难?其实不然。创建一个新线程,用std::thread就能轻松搞定。下面这个例子,能让你直观地感受线程是怎么“跑”起来的。

#include 
#include 

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

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

2. 线程同步

线程一旦多起来,麻烦也就跟着来了。最典型的问题就是数据竞争:多个线程同时读写一块共享内存,结果很可能一团糟。这时候,同步机制就该登场了,互斥锁(std::mutex)就是其中最常用的一种“交通警察”。

#include 
#include 
#include 

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;
}

3. 条件变量

光有锁还不够。有时候,线程需要等待某个条件成立才能继续执行,比如等待任务队列非空。这种场景下,条件变量(std::condition_variable)就是最佳拍档,它通常和互斥锁携手工作,实现更精细的线程间协调。

#include 
#include 
#include 
#include 

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

void printId(int id) {
    std::unique_lock lck(mtx);
    cv.wait(lck, []{return ready;}); // 等待直到ready为true
    std::cout << “Thread ” << id << std::endl;
}

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(printId, i);

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

    for (auto& th : threads) th.join();
    return 0;
}

4. 原子操作

锁用多了,性能难免受影响。对于一些简单的操作,比如计数器增减,有没有更轻量级的方案?答案是肯定的,那就是原子操作(std::atomic)。它能在硬件层面保证操作的不可分割性,从而实现高效的无锁编程。

#include 
#include 
#include 

std::atomic counter(0);

void incrementCounter() {
    for (int i = 0; i < 1000; ++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;
}

编译和运行

纸上谈兵终觉浅。在Ubuntu上把代码变成可执行文件,这一步很关键。使用g++编译器时,记住要加上-pthread参数来链接线程库。

g++ -pthread your_program.cpp -o your_program
./your_program

以上这些,算是C++并发编程的“入门四式”。它们涵盖了创建、同步、协调和高效访问这几个基本维度。当然,实际项目中的挑战往往更复杂,需要根据具体的应用场景,灵活组合甚至设计更高级的并发控制策略。但万变不离其宗,理解了这些基础,后面的路就好走多了。

本文转载于:https://www.yisu.com/ask/36866482.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注