最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Ubuntu C++怎样实现并发编程
时间:2026-07-15 19:38:48 编辑:袖梨 来源:一聚教程网
在Ubuntu上使用C++实现并发编程,你可以选择多种方法。以下是一些常见的并发编程技术:

- 多线程 - 使用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;}- 互斥锁 - 使用
<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;}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...n";go(); // go!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: " << 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...n";int value = result.get(); // 获取异步操作的结果std::cout << "Got the result: " << value << std::endl;return 0;}- 并行算法 - C++17引入了并行算法,可以使用
<execution>头文件中的执行策略来并行化标准库算法。
#include <iostream>#include <vector>#include <algorithm>#include <execution>int main() {std::vector<int> v = {1, 2, 3, 4, 5};// 使用并行执行策略来排序std::sort(std::execution::par, v.begin(), v.end());for (int i : v) {std::cout<< i << ' ';}std::cout << 'n';return 0;}在编译C++程序时,如果你使用了C++11或更高版本的特性,确保在编译命令中添加-std=c++11(或更高版本的标志,如-std=c++17)以及-pthread(如果你使用了线程)。
例如:
g++ -std=c++11 -pthread your_program.cpp -o your_program这些是C++中实现并发编程的一些基本方法。根据你的具体需求,你可能需要结合使用这些技术来实现更复杂的并发模式。
相关文章
- 适合小学生玩的游戏推荐 2026小学生喜欢玩的游戏合集 07-15
- 日式rpg游戏合集 2026最受欢迎的日式rpg游戏大盘点 07-15
- 濡沫江湖洛阳郊外隐藏宝箱具体位置一览 07-15
- 暗黑破坏神4怎么堆叠减伤 暗黑破坏神4堆减伤攻略 07-15
- tavo角色卡怎么导入 07-15
- 2026年3-6岁儿童益智游戏APP推荐:寓教于乐的优质之选 07-15