如何避免种族状况? [英] How to avoid race condition?

查看:85
本文介绍了如何避免种族状况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将与Flutter和Firestore做一个随机的1:1聊天应用程序.但是当我连接第二个用户聊天时,我有比赛条件.

I am make random 1:1 chat app with Flutter and Firestore. But I have race condition when I am connect second user to chat.

这是我的客户端应用代码,用于将第二个用户添加到Firestore(第一个用户已经添加到Firestore文档中):

This my client app code for add second user to Firestore (first user is already add to Firestore document):

await chatRoomReference.setData({
  ‘secondUserUID': uid,
});

第二位用户点击聊天时,我是删除选项,可从所有客户端UI进入此聊天室.但是,如果第三位用户同时点击聊天(在UI从流中获取更新之前),则可能会将他也添加到数据库中.聊天不允许这样做.

When second user tap to chat I am remove option to enter this chatroom from all client UI. But is possible that if third user tap to chat at same time (before UI get update from stream) he will also be add to database. Chat should not allow this. 


如何避免比赛条件?

谢谢!

更新:

每个聊天用户都作为新文档添加到单独的用户聊天集中.

Each chat user is add as new document in separate user collection for chat.

推荐答案

我认为您的按钮应该先检查聊天室中的人数,然后再加入聊天室.

I think your button should check the number of people in the chat room then join the chat room.

checkBeforeJoinTheChatRoom()
    .then((numbOfPeople){
        if(numbOfPeople < 2){ 
            joinChat();
        }
    }
)

在您的情况下,交易可能有效:

transaction may work in your case:

final DocumentReference postRef = Firestore.instance.document('posts/123');
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    await tx.update(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
  }
});

详细了解以下内容: cloud_firestore_transactions

这篇关于如何避免种族状况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆