在Linux环境下使用C++进行多线程编程时,资源管理是一个重要的考虑因素。以下是一些关键的管理策略和实践:
互斥锁是保护共享资源的基本工具。通过std::mutex
和std::lock_guard
或std::unique_lock
,可以确保同一时间只有一个线程访问共享资源。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int shared_resource = 0;
void thread_func() {
std::lock_guard<std::mutex> lock(mtx);
shared_resource++;
std::cout << "Shared resource: " << shared_resource << std::endl;
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
t1.join();
t2.join();
return 0;
}
条件变量用于线程间的同步,允许线程等待某个条件成立。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int shared_resource = 0;
bool ready = false;
void thread_func() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
shared_resource++;
std::cout << "Shared resource: " << shared_resource << std::endl;
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_all();
t1.join();
t2.join();
return 0;
}
原子操作是不可中断的操作,适用于简单的计数器等场景。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> shared_resource(0);
void thread_func() {
shared_resource++;
std::cout << "Shared resource: " << shared_resource.load() << std::endl;
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
t1.join();
t2.join();
return 0;
}
RAII是一种C++编程技巧,通过对象的构造和析构来管理资源。在多线程环境中,可以使用std::lock_guard
和std::unique_lock
来自动管理互斥锁的生命周期。
死锁是多线程编程中的常见问题。确保在获取多个锁时遵循一致的顺序,并使用超时机制来避免无限等待。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx1, mtx2;
void thread_func1() {
std::unique_lock<std::mutex> lock(mtx1);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::unique_lock<std::mutex> lock2(mtx2);
// Do something
}
void thread_func2() {
std::unique_lock<std::mutex> lock(mtx2);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::unique_lock<std::mutex> lock1(mtx1);
// Do something
}
int main() {
std::thread t1(thread_func1);
std::thread t2(thread_func2);
t1.join();
t2.join();
return 0;
}
线程池可以有效地管理线程资源,避免频繁创建和销毁线程的开销。
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
template<class F, class... Args>
void enqueue(F&& f, Args&&... args) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace([f, args...] { f(args...); });
}
condition.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop = false;
};
void thread_func(int id) {
std::cout << "Thread " << id << " is running" << std::endl;
}
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue(thread_func, i);
}
return 0;
}
通过以上策略和实践,可以有效地管理Linux环境下C++多线程程序中的资源。