21xrx.com
2025-06-11 18:59:48 Wednesday
登录
文章检索 我的文章 写文章
C++ select 多线程编程实例
2023-07-12 12:31:07 深夜i     24     0
C++ Select 多线程编程 实例

C++ 是一种高效的编程语言,使用它可以编写出高性能的程序。为了充分利用多核处理器的优势,我们可以使用多线程编程技术来实现并行计算。在 C++ 中,经典的多线程编程模型是 POSIX 线程库,它提供了基本的线程管理和同步机制。但是,POSIX 线程库的使用比较繁琐,容易出错。为了方便地开发多线程程序,我们可以使用 C++11 提供的标准库,它提供了高级线程管理和同步机制。本文将介绍如何使用 C++ 标准库中的 select 函数实现多线程编程。

select 函数是一种 I/O 多路复用技术,它可以同时监视多个 I/O 句柄的状态,包括文件描述符、套接字和管道等。当任何一个 I/O 句柄就绪时,select 函数就会返回。使用 select 函数可以避免阻塞,提高程序的效率。在多线程编程中,我们可以使用 select 函数来实现多个线程之间的通信和同步。

下面是一个使用 select 函数实现多线程编程的示例程序:

#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <unistd.h>
#include <sys/select.h>
#include <fcntl.h>
using namespace std;
int main()
{
  vector<int> pipes;
  int max_fd = 0;
  fd_set read_fds;
  atomic_bool stop_flag(false);
  for (int i = 0; i < 5; i++)
  {
    int fd[2];
    if (pipe(fd) < 0)
    {
      cerr << "Error: unable to create pipe" << endl;
      exit(1);
    }
    int flags = fcntl(fd[0], F_GETFL, 0);
    fcntl(fd[0], F_SETFL, flags | O_NONBLOCK);
    pipes.push_back(fd[0]);
    if (fd[0] > max_fd) max_fd = fd[0];
    thread t{[&stop_flag, fd](){
      while (!stop_flag) {
        ::write(fd[1], "Hello", 5);
        this_thread::sleep_for(chrono::milliseconds(100));
      }
    }};
    t.detach();
  }
  while (!stop_flag) {
    FD_ZERO(&read_fds);
    for (auto pipe : pipes) {
      FD_SET(pipe, &read_fds);
    }
    int ret = select(max_fd + 1, &read_fds, nullptr, nullptr, nullptr);
    if (ret < 0)
    {
      cerr << "Error: unable to select" << endl;
      exit(1);
    }
    for (auto pipe : pipes) {
      if (FD_ISSET(pipe, &read_fds)) {
        char buf[256];
        ::read(pipe, buf, sizeof(buf));
        cout << "Received: " << buf << endl;
      }
    }
  }
  return 0;
}

该程序创建了 5 个线程,每个线程都向一个管道写入 "Hello" 字符串,间隔 100 毫秒。主线程使用 select 函数监视这 5 个管道,当有任何一个管道就绪时,就读取管道中的数据,并输出到屏幕上。程序运行时会一直输出 "Received: Hello" 字符串,直到按下 Ctrl+C 终止程序。

上面的程序使用了 C++11 中的标准库,代码比较简洁。使用标准库可以方便地创建线程、使用原子变量和 lambda 表达式等先进的语言特性。使用 select 函数来实现多线程编程也非常方便,可以方便地避免阻塞和死锁问题。如果你需要编写高性能的多线程程序,可以考虑使用这种技术来提高效率。

  
  

评论区