Ubuntu C++怎样进行并发编程与同步
导读:在Ubuntu上进行C++并发编程,你可以使用C++11标准库中提供的线程支持库 <thread>,以及同步原语,如互斥锁 <mutex>、条件变量 <condition_variable>、原子操作 &...
在Ubuntu上进行C++并发编程,你可以使用C++11标准库中提供的线程支持库 <
thread>
,以及同步原语,如互斥锁 <
mutex>
、条件变量 <
condition_variable>
、原子操作 <
atomic>
等。下面是一些基本的示例和说明。
1. 使用 <
thread>
进行并发编程
首先,确保你的编译器支持C++11或更高版本。使用 -std=c++11 或 -std=c++17 等选项来启用C++11特性。
#include <
iostream>
#include <
thread>
void helloFunction() {
std::cout <
<
"Hello from a thread!" <
<
std::endl;
}
int main() {
// 创建一个线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout <
<
"Hello from main!" <
<
std::endl;
return 0;
}
编译并运行:
g++ -std=c++11 -pthread your_file.cpp -o your_program
./your_program
2. 使用 <
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. 使用 <
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. 使用 <
atomic>
进行原子操作
原子操作是不可分割的操作,可以用来实现无锁编程。
#include <
iostream>
#include <
thread>
#include <
atomic>
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 <
<
std::endl;
return 0;
}
在Ubuntu上进行C++并发编程时,确保你的代码正确地处理了线程的创建、同步和销毁。错误地管理线程可能导致死锁、竞态条件和其他并发问题。使用上述工具和技巧可以帮助你编写出健壮的并发程序。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu C++怎样进行并发编程与同步
本文地址: https://pptw.com/jishu/747187.html
