在CentOS上实现C++并发编程,你可以使用多种方法。以下是一些常见的并发编程技术:
<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;
}
<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;
}
<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;
}
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;
    {
        std::lock_guard<std::mutex> lck(mtx);
        ready = true;
    }
    cv.notify_all(); // 通知所有线程
    for (auto &th : threads) th.join();
    return 0;
}
<atomic>来实现无锁的并发数据结构。#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void incrementCounter() {
    for (int i = 0; i < 1000; ++i) {
        counter++;
    }
}
int main() {
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);
    t1.join();
    t2.join();
    std::cout << "Counter value: " << counter << std::endl;
    return 0;
}
<future>和<async>来执行异步任务。#include <iostream>
#include <future>
int asyncFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 42;
}
int main() {
    std::future<int> result = std::async(std::launch::async, asyncFunction);
    // 可以在这里做其他事情
    std::cout << "Waiting for the result..." << std::endl;
    // 获取异步任务的结果
    int value = result.get();
    std::cout << "Result: " << value << std::endl;
    return 0;
}
在CentOS上编译C++并发程序时,确保使用支持C++11或更高标准的编译器选项,例如使用g++时添加-std=c++11或-std=c++17。
g++ -std=c++11 -pthread your_program.cpp -o your_program
-pthread选项用于启用POSIX线程支持,这对于多线程编程是必要的。如果你使用的是C++11以上的其他并发特性,如<future>和<async>,则不需要-pthread选项,但仍然需要-std=c++11或更高版本的标准选项。