简体   繁体   English

可以在PHP / PostGresql(这是一个在线排队站点)中发生竞争状况吗?

[英]Can race condition occur in PHP / PostGresql (This is for an online queuing site)?

I am creating an online queuing site. 我正在创建一个在线排队站点。 First, a user logs on the web app. 首先,用户登录Web应用程序。 On his first sign-in, he is assigned a queue number(which will be used to determine a user's order during an onsite event). 首次登录时,系统会为他分配一个队列号(该队列号将用于在现场事件期间确定用户的订单)。 Will a race condition occur? 会发生比赛状况吗? Expected users are between 600-1000 . 预期用户在600-1000之间。

I don't want any conflicts when the queue number of a user is being determined. 确定用户的队列号时,我不希望有任何冲突。 I plan to assign a queue number by keeping track in the database of the last queue number given, and then increment that by 1 and assign that number to a User's "Queue_NO.". 我计划通过跟踪数据库中给定的最后一个队列号来分配一个队列号,然后将其递增1并将该编号分配给用户的“ Queue_NO”。

Where user is an entity in the database. 用户是数据库中的实体。

I guess the best way would be to make a table called event_queue and generate numbers with auto increment. 我猜最好的方法是制作一个名为event_queue的表并自动递增生成数字。

id
id_event
id_user

can be the fields. 可以是字段。 When a new user signs in for an event, create a new entry to event queue and the id will be her queue number 当新用户登录事件时,请为事件队列创建一个新条目,该ID将是她的队列号

The conflict might happen, indeed, but that is okay. 确实可能发生冲突,但这没关系。

With transactional databases a data modification query might fail because of conflicts. 对于事务数据库,由于冲突,数据修改查询可能会失败。 The database will detect a conflicts and report it. 数据库将检测到冲突并报告。 (For example with a " could not serialize access due to concurrent update " error message). 例如 ,带有“ could not serialize access due to concurrent update ”错误消息)。 It is a common practice to check the status of the transaction and repeat it if a conflict happened. 通常的做法是检查交易的状态,并在发生冲突时重复进行。

Similarly, when you insert a new queue number into the database you must check if the transactional is sucessful and repeat it if it isn't. 同样,当您向数据库中插入新的队列号时,必须检查事务处理是否成功,否则请重复进行。

You can create an autoincrement as Ali suggested but I often prefer the simpler "max + 1" logic. 您可以按照Ali的建议创建自动增量 ,但我通常更喜欢简单的“ max + 1”逻辑。

Notice, however, that the autoincrement and the "max + 1" behave differently: if you delete a number of entries at the end of the queue (or if some insert transactions rollback), the "max + 1" approach will reuse their numbers. 但是请注意, 自动递增和“ max + 1”的行为不同:如果删除队列末尾的多个条目(或者某些插入事务回滚),则“ max +1”方法将重用其数字。 The autoincrement will leave these numbers unused. 自动递增将不使用这些数字。

PS An example: http://sqlfiddle.com/#!15/06b87/7 PS示例: http : //sqlfiddle.com/#!15/06b87/7

CREATE TABLE queue (id INTEGER NOT NULL PRIMARY KEY);
INSERT INTO queue SELECT COALESCE (MAX (id) + 1, 1) FROM queue RETURNING id;

(See also postgreSQL function for last inserted ID ). (有关最后插入的ID,另请参见postgreSQL函数 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM