我有一个读写数据库的方法。它会检查用户数量是否小于MAX_USERS,然后添加一个新用户。请参考以下代码:
addUser(User user){
//count number of users in the DB, SELECT count(*) from user_table
count = ...
if(count<MAX_USERS){
//add the new user to the DB, INSERT INTO users_table
}
}
这里的问题是,如果以上代码被多个线程调用,则可能会获得相同的计数值。这将导致users_table中的条目超过MAX_USERS。
一种解决方法是同步整个方法,但这将影响性能。有没有更好的处理方式?