21xrx.com
2025-02-12 06:06:18 Wednesday
登录
文章检索 我的文章 写文章
"C++中使用queue.h头文件的示例"
2023-07-03 08:17:08 深夜i     --     --
C++编程 queue h头文件 队列数据结构 FIFO 示例代码

C++是一种广泛使用的编程语言,它具有丰富的内置数据结构和算法库,其中包括队列。要使用队列,我们需要在C++程序中包含一个名为“queue.h”的头文件。在这篇文章中,我们将介绍如何在C++程序中使用queue.h头文件。

首先,让我们创建一个简单的程序来说明如何使用queue.h头文件。假设我们想要创建一个程序来模拟一个线程池,其中包含10个线程执行任务。我们可以使用队列来存储等待执行的任务,然后按顺序将它们发送给可用的线程。

下面是一个使用queue.h头文件实现上述功能的示例程序:


#include <iostream>

#include <queue>

#include <thread>

using namespace std;

int main() {

 int num_threads = 10;

 queue<int> task_queue;

 // Add tasks to the task queue

 for (int i = 0; i < 100; i++) {

  task_queue.push(i);

 }

 // Start the threads and make them wait for tasks

 vector<thread> threads(num_threads);

 for (int i = 0; i < num_threads; i++) {

  threads[i] = thread([&]() {

   while (true) {

    int task;

    // Pop a task from the queue or wait for a new task

    {

     unique_lock<mutex> lock(task_queue_mutex);

     while (task_queue.empty()) {

      task_queue_condition.wait(lock);

     }

     task = task_queue.front();

     task_queue.pop();

    }

    // Execute the task

    cout << "Thread " << this_thread::get_id() << " executed task " << task << endl;

   }

  });

 }

 // Add a sentinel task to terminate all the threads

 for (int i = 0; i < num_threads; i++) {

  task_queue.push(-1);

 }

 // Wait for all the threads to finish

 for (int i = 0; i < num_threads; i++) {

  threads[i].join();

 }

 cout << "All threads finished." << endl;

 return 0;

}

这个程序使用了std::queue模板类来实现任务队列。然后使用std::thread类来启动10个线程执行任务。每个线程都会一直等待,直到任务队列中有可以执行的任务。一旦发现队列中有任务,线程就会将其从队列中弹出并执行。线程将继续等待任务,直到收到终止信号。

task_queue_mutex和task_queue_condition是std::mutex和std::condition_variable类的实例,用于协调线程之间的任务队列访问。在每个线程中,他先要等待task_queue_condition,直到task_queue 非空可pop task。在主线程中,添加了一个特殊任务-1到任务队列来停止所有线程。最后,主线程等待所有线程完成后,输出“All threads finished.”来结束程序。

在此示例程序中,我们使用了std::queue、std::thread、std::mutex和std::condition_variable类,这四个类都是C++标准库中提供的类,被包含在queue.h头文件中。其他的常用C++头文件还包括 algorithm.h, math.h, string.h和vector.h。

在C++编程中使用queue.h头文件可以帮助简化开发过程,提供了许多有用的数据结构和算法,让开发者可以更快地开发出高效的程序。通过使用这些标准库类,我们可以很容易地实现常见的编程任务,如线程池,工作队列,广度优先搜索等等。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复