我正在编写一个应用程序,其中服务器必须跟踪来自多个客户端的连接。每个客户端都被分配了一个连接 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/