2013-02-20 46 views
1

我正在编写一个应用程序,其中服务器必须跟踪来自多个客户端的连接。每个客户端都分配了一个连接ID,它将在每个数据包中发送以进行标识。我想将连接ID​​映射到客户端信息。早些时候,我使用std :: map,但我发现它不是线程安全的。我需要一个可以在纯C++ 03中支持此功能的容器。没有第三方库允许(使用实验室设备)。如果没有这个,请告诉我如何使用std :: map和某种锁定来实现这一点。我们调用数据结构info.There有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]; 
     } 
} 
+0

如果您使用的是C++ 11,请考虑检查http://en.cppreference.com/w/cpp/thread – 2013-02-20 18:51:32

+0

不可以。也许我应该添加,古老的实验室电脑:) – 2013-02-20 20:12:54

回答

1

使用__sync_fetch_and_add获得下一个CONNID并使用pthread互斥来包装您的其他地图调用。

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]; 

} 
+0

这对我来说看起来不合标准?但我正在寻找这样的答案 – 2013-02-20 20:09:21

+0

@Bug Catcher - “标准”方法将是一个包装类,它使用map作为基础,并使用互斥锁来同步方法调用。 – 2013-02-20 20:17:31

+0

实际上,我生成一个随机连接ID,所以同步并不是必要的,也许这个解决方案不足以作为地图迭代器可能由于在键迭代时插入而变得无效? – 2013-02-20 20:48:27

0

你必须通过互斥来保护你的容器。取决于用于启动线程的api,它将是pthread_mutex_t或std :: mutex

相关问题