21xrx.com
2025-03-27 16:55:31 Thursday
文章检索 我的文章 写文章
C++ 多线程同步方法详解
2023-07-04 14:44:37 深夜i     61     0
C++ 多线程 同步方法 Mutex Condition Variable

C++是一种广泛使用的编程语言,其多线程功能也备受开发人员的青睐。在使用C++进行多线程编程时,需要一些同步方法来确保程序的正确性和可靠性。下面将详细介绍C++的多线程同步方法。

1. 互斥锁

互斥锁是一种最常用的多线程同步方法,它可以防止多个线程同时访问共享数据。当一个线程获得了互斥锁后,其他线程就无法获得该锁,直到持有锁的线程释放锁为止。在C++中,互斥锁是通过std::mutex类来实现的。以下是一个互斥锁的示例程序:

#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void thread_func(int n)
{
  mtx.lock(); // 阻塞其他线程,获得互斥锁
  std::cout << "Thread " << n << " start." << std::endl;
  // 执行线程任务
  std::cout << "Thread " << n << " end." << std::endl;
  mtx.unlock(); // 释放互斥锁,允许其他线程访问共享资源
}
int main()
{
  std::thread t1(thread_func, 1);
  std::thread t2(thread_func, 2);
  t1.join();
  t2.join();
  return 0;
}

2. 条件变量

条件变量是一种能够阻塞线程并等待某个条件发生的多线程同步方法。当一个线程需要等待另一个线程达到某个特定状态时,就可以使用条件变量来实现。在C++中,条件变量是通过std::condition_variable类来实现的。以下是一个条件变量的示例程序:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx; // 全局互斥锁
std::condition_variable cv; // 全局条件变量
bool ready = false; // 全局条件变量状态
void thread_func(int n)
{
  std::unique_lock<std::mutex> lk(mtx); // 互斥锁作为条件变量锁
  while (!ready)
  {
    cv.wait(lk); // 阻塞线程并等待条件变量
  }
  // 执行线程任务
  std::cout << "Thread " << n << " start." << std::endl;
  std::cout << "Thread " << n << " end." << std::endl;
}
int main()
{
  std::thread t1(thread_func, 1);
  std::thread t2(thread_func, 2);
  std::this_thread::sleep_for(std::chrono::seconds(2)); // 睡眠2秒
  ready = true; // 改变条件变量状态
  cv.notify_all(); // 唤醒在条件变量上等待的所有线程
  t1.join();
  t2.join();
  return 0;
}

3. 信号量

信号量是一种用于多线程同步的计数器,它可以控制同一时间内访问共享数据的线程数目。在C++中,信号量是通过std::semaphore类来实现的。以下是一个信号量的示例程序:

#include <iostream>
#include <thread>
#include <semaphore.h>
sem_t sem; // 全局信号量
void thread_func(int n)
{
  sem_wait(&sem); // 阻塞线程并等待信号量变为大于0
  // 执行线程任务
  std::cout << "Thread " << n << " start." << std::endl;
  std::cout << "Thread " << n << " end." << std::endl;
  sem_post(&sem); // 提高信号量,允许下一个线程访问共享资源
}
int main()
{
  sem_init(&sem, 0, 1); // 初始化为1
  std::thread t1(thread_func, 1);
  std::thread t2(thread_func, 2);
  t1.join();
  t2.join();
  sem_destroy(&sem);
  return 0;
}

以上是C++多线程同步方法的详细介绍,每种方法都有其适用场合和注意事项,在实际编程中需要根据需求进行选择和使用。

  
  

评论区