21xrx.com
2025-03-31 14:00:50 Monday
文章检索 我的文章 写文章
C++三个线程顺序输出ABC
2023-07-04 23:31:04 深夜i     37     0
C++ 三个线程 ABC 顺序输出

在多线程编程中,控制线程的执行顺序是一个经典问题。在C++中,通过使用同步原语和条件变量等工具,可以轻松实现三个线程的顺序输出ABC。

首先,我们需要定义三个线程,分别代表A、B、C。我们可以使用C++11中的std::thread类来实现:

#include <iostream>
#include <thread>
void threadA()
  std::cout << "A" << std::endl;
void threadB()
  std::cout << "B" << std::endl;
void threadC()
  std::cout << "C" << std::endl;
int main() {
  std::thread t1(threadA);
  std::thread t2(threadB);
  std::thread t3(threadC);
  t1.join();
  t2.join();
  t3.join();
  return 0;
}

接下来,我们需要使用条件变量来控制线程的执行顺序。条件变量是C++标准库中的一个同步原语,用于等待线程满足某些条件。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable condVar;
bool ready = false;
void threadA() {
  std::unique_lock<std::mutex> lock(mtx);
  while(!ready) {
    condVar.wait(lock);
  }
  std::cout << "A" << std::endl;
}
void threadB() {
  std::unique_lock<std::mutex> lock(mtx);
  while(!ready) {
    condVar.wait(lock);
  }
  std::cout << "B" << std::endl;
}
void threadC() {
  std::unique_lock<std::mutex> lock(mtx);
  while(!ready) {
    condVar.wait(lock);
  }
  std::cout << "C" << std::endl;
}
int main() {
  std::thread t1(threadA);
  std::thread t2(threadB);
  std::thread t3(threadC);
  {
    std::unique_lock<std::mutex> lock(mtx);
    ready = true;
    condVar.notify_all();
  }
  t1.join();
  t2.join();
  t3.join();
  return 0;
}

在上面的代码中,我们首先定义了一个互斥量(std::mutex)和一个条件变量(std::condition_variable)。然后在每一个线程中,我们使用while循环等待ready变量为true,表示当前线程可以执行。在主函数中,我们将ready变量设置为true,并通过notify_all()函数通知所有线程可以开始执行。

最终的输出结果为ABC,表示三个线程的顺序执行成功。

综上所述,通过使用条件变量等工具,C++可以轻松实现多线程的顺序控制。在实际开发中,我们可以根据具体需求进行扩展和优化,使多线程程序更加高效稳定。

  
  

评论区