ubuntu

Ubuntu C++并发编程如何实现

小樊
56
2025-04-18 09:02:31
栏目: 编程语言

在Ubuntu上进行C++并发编程,你可以使用多种方法和技术。以下是一些常见的并发编程方法:

  1. C++11线程库: C++11引入了标准线程库,它提供了std::thread类来创建和管理线程。这是一个跨平台的解决方案,可以在Ubuntu上使用。

    #include <iostream>
    #include <thread>
    
    void helloFunction() {
        std::cout << "Hello from a thread!" << std::endl;
    }
    
    int main() {
        std::thread t(helloFunction);
        t.join(); // 等待线程完成
        return 0;
    }
    
  2. 互斥锁: 当多个线程需要访问共享资源时,可以使用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;
    }
    
  3. 条件变量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;
    }
    
  4. 原子操作std::atomic提供了原子操作,可以在多线程环境中安全地进行某些操作,而不需要显式的锁。

    #include <iostream>
    #include <thread>
    #include <atomic>
    
    std::atomic<int> sharedValue(0);
    
    void incrementValue() {
        ++sharedValue; // 原子操作
    }
    
    int main() {
        std::thread t1(incrementValue);
        std::thread t2(incrementValue);
    
        t1.join();
        t2.join();
    
        std::cout << "Shared value: " << sharedValue << std::endl;
    
        return 0;
    }
    
  5. 异步任务: C++11还提供了std::asyncstd::future来执行异步任务,并获取它们的结果。

    #include <iostream>
    #include <future>
    
    int compute(int x) {
        return x * x;
    }
    
    int main() {
        std::future<int> result = std::async(std::launch::async, compute, 42);
        std::cout << "The answer is " << result.get() << std::endl; // 获取异步任务的结果
        return 0;
    }
    
  6. 线程池: 虽然C++标准库没有直接提供线程池的实现,但你可以使用第三方库,如Boost.Asio或者自己实现一个简单的线程池。

在Ubuntu上编译C++并发程序时,确保使用支持C++11或更高标准的编译器选项,例如:

g++ -std=c++11 -pthread your_program.cpp -o your_program

-pthread选项告诉编译器链接线程支持库,并启用相关的预处理器定义。

0
看了该问题的人还看了