阅读量:134
在Linux环境下使用C++进行并发编程,主要依赖于POSIX线程库(pthread)和C++11引入的线程库。以下是一些基本的步骤和示例代码,帮助你开始使用C++进行并发编程。
1. 使用POSIX线程库(pthread)
安装pthread
大多数Linux发行版默认已经安装了pthread库。如果没有安装,可以使用包管理器进行安装。例如,在Ubuntu上可以使用以下命令:
sudo apt-get install libpthread-stubs0-dev
示例代码:创建和销毁线程
#include
#include
void* thread_function(void* arg) {
std::cout << "Thread is running" << std class="hljs-keyword">return nullptr;
}
int main() {
pthread_t thread_id;
int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Failed to create thread" << std class="hljs-keyword">return 1;
}
pthread_join(thread_id, nullptr);
std::cout << "Thread has finished" << std class="hljs-keyword">return 0;
}
2. 使用C++11线程库
C++11引入了标准线程库,提供了更现代和类型安全的接口。
示例代码:创建和销毁线程
#include
#include
void thread_function() {
std::cout << "Thread is running" << std class="hljs-function">int main() {
std::thread t(thread_function);
if (!t.joinable()) {
std::cerr << "Failed to create thread" << std class="hljs-keyword">return 1;
}
t.join();
std::cout << "Thread has finished" << std class="hljs-keyword">return 0;
}
3. 线程同步
互斥锁(mutex)
互斥锁用于保护共享数据,防止多个线程同时访问。
pthread示例
#include
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* increment_counter(void* arg) {
for (int i = 0; i < 100000; ++i) {
pthread_mutex_lock(&mutex);
// Critical section
int* counter = static_cast<int*>(arg);
++(*counter);
pthread_mutex_unlock(&mutex);
}
return nullptr;
}
int main() {
int counter = 0;
pthread_t threads[10];
for (int i = 0; i < 10; ++i) {
pthread_create(&threads[i], nullptr, increment_counter, &counter);
}
for (int i = 0; i < 10; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "Counter value: " << counter class="hljs-keyword">return 0;
}
C++11示例
#include
#include
#include
std::mutex mtx;
void increment_counter(int& counter) {
for (int i = 0; i < 100000; ++i) {
std::lock_guard lock(mtx) ;
// Critical section
++counter;
}
}
int main() {
int counter = 0;
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(increment_counter, std::ref(counter));
}
for (auto& t : threads) {
t.join();
}
std::cout << "Counter value: " << counter class="hljs-keyword">return 0;
}
条件变量(condition variable)
条件变量用于线程间的同步,允许一个线程等待某个条件成立。
pthread示例
#include
#include
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool ready = false;
void* wait_for_signal(void* arg) {
pthread_mutex_lock(&mutex);
while (!ready) {
pthread_cond_wait(&cond, &mutex);
}
std::cout << "Signal received" << std class="hljs-built_in">pthread_mutex_unlock(&mutex);
return nullptr;
}
void send_signal() {
sleep(2); // Simulate some work
pthread_mutex_lock(&mutex);
ready = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_t thread;
pthread_create(&thread, nullptr, wait_for_signal, nullptr);
send_signal();
pthread_join(thread, nullptr);
return 0;
}
C++11示例
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void wait_for_signal() {
std::unique_lock lock(mtx) ;
cv.wait(lock, []{ return ready; });
std::cout << "Signal received" << std class="hljs-function">void send_signal() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // Simulate some work
std::lock_guard lock(mtx) ;
ready = true;
cv.notify_one();
}
int main() {
std::thread thread(wait_for_signal);
send_signal();
thread.join();
return 0;
}
4. 线程池
线程池是一种管理线程的机制,可以提高性能和资源利用率。
示例代码:简单的线程池
#include
#include
#include
#include
#include
#include
#include
#include
class ThreadPool {
public:
ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads class="hljs-built_in">emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock lock(this->queue_mutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_sharedreturn_type()>>(
std::bind(std::forward(f), std::forward(args)...)
);
std::future res = task->get_future();
{
std::unique_lock lock(queue_mutex) ;
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
~ThreadPool() {
{
std::unique_lock lock(queue_mutex) ;
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
private:
std::vector workers;
std::queuevoid()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4);
auto result = pool.enqueue([](int answer) { return answer; }, 42);
std::cout << "Result: " << result class="hljs-built_in">get() << std class="hljs-keyword">return 0;
}
通过这些示例代码,你可以开始在Linux环境下使用C++进行并发编程。根据具体需求,你可以进一步扩展和优化这些代码。