阅读量:25
在Ubuntu上进行C++并发编程,你可以使用C++11标准库中提供的线程支持库 ,以及同步原语,如互斥锁 、条件变量 、原子操作 等。下面是一些基本的示例和说明。
1. 使用 进行并发编程
首先,确保你的编译器支持C++11或更高版本。使用 -std=c++11 或 -std=c++17 等选项来启用C++11特性。
#include
#include
void helloFunction() {
std::cout << "Hello from a thread!" << std class="hljs-function">int main() {
// 创建一个线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from main!" << std class="hljs-keyword">return 0;
}
编译并运行:
g++ -std=c++11 -pthread your_file.cpp -o your_program
./your_program
2. 使用 进行同步
互斥锁用于保护共享资源,防止多个线程同时访问。
#include
#include
#include
std::mutex mtx; // 创建一个互斥锁
void printMessage(const std::string& msg) {
mtx.lock(); // 锁定互斥锁
std::cout << msg class="hljs-built_in">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. 使用 进行线程间通信
条件变量允许线程等待某个条件成立。
#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;}); // 等待条件变量
std::cout << "Thread " << id class="hljs-function">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 class="hljs-built_in">go(); // go!
for (auto &th : threads) th.join();
return 0;
}
4. 使用 进行原子操作
原子操作是不可分割的操作,可以用来实现无锁编程。
#include
#include
#include
std::atomic<int> counter(0);
void incrementCounter() {
for (int i = 0; i < 100000; ++i) {
counter++; // 原子操作
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter: " << counter class="hljs-keyword">return 0;
}
在Ubuntu上进行C++并发编程时,确保你的代码正确地处理了线程的创建、同步和销毁。错误地管理线程可能导致死锁、竞态条件和其他并发问题。使用上述工具和技巧可以帮助你编写出健壮的并发程序。