c++ - 用于保存客户信息的线程安全数据结构

标签 c++ linux sockets dictionary pthreads

我正在编写一个应用程序,其中服务器必须跟踪来自多个客户端的连接。每个客户端都被分配了一个连接 ID,它在每个数据包中发送该 ID 以供识别。我想将连接 ID 映射到客户端信息。早些时候,我使用的是 std::map 但我发现它不是线程安全的。我需要一个可以在纯 C++03 中支持此功能的容器。不允许使用第 3 方库(使用实验室设备)。如果做不到这一点,请告诉我如何使用 std::map 和某种锁定来实现这一点

让我们调用数据结构信息。有 2 个线程在运行,(分别用于发送和接收)。他们对信息执行以下操作:-

recv_thread {
  //read id
  if(id == 0) info.insert(0,clientdata);
  else {
       do stff, update info[id]
}

send_thread { 
     for each key in info:
       if (key==0) {
          delete info[0];
          info.insert(connid, clientdata);
       }
       else {
           update info[key]
           if(client taking too long) delete info[key];
       }
 }

最佳答案

使用 __sync_fetch_and_add 获取下一个 connid 并使用 pthread mutex 包装您的其他 map 调用。

pthread_mutex_t mutex;
int nextConnid = 1;
...
pthread_mutex_init(&mutex, NULL);
...
recv_thread {
  //read id
  if(id == 0) 
    info.insert(__sync_fetch_and_add(&nextConnid, 1), clientdata);
  else {
       do stff, 
       pthread_mutex_lock(&mutex);
       update info[id]
       pthread_mutex_unlock(&mutex);
}

send_thread { 
     for each key in info:
           pthread_mutex_lock(&mutex);
           update info[key]
           pthread_mutex_unlock(&mutex);
           if(client taking too long) delete info[key];

 }

关于c++ - 用于保存客户信息的线程安全数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987489/

相关文章:

php - file_put_contents(文件路径/文件)[function.file-put-contents] : failed to open stream: Permission denied

java - Matlab 与 Java 中运行的 Java 守护进程的连接

c++ - 确定未绑定(bind)套接字的地址族

javascript - 使用事件的feathersjs套接字

c++ - 如何将值从主机字节顺序转换为小尾数?

c++ - 如何在 OpenCV 中将图像调整为特定大小?

linux - grep/根据第一个文件中的列表从第二个文件中获取字符串

python - UDP Socket 没有收到任何带有 python 的消息

c++ - 自动释放资源的通用句柄

c++ - 从 ‘int (*)()’ 到 ‘int’ [-fpermissive] 的无效转换