我有一张 table ,例如股票
:
SELECT * FROM stock;
+------------+----------+
| product_id | quantity |
+------------+----------+
| 1 | 100 |
+------------+----------+
我想模拟并发提交订单并同时减少库存:
UPDATE store SET quantity = quantity-${count} WHERE product_id = ${product_id}
我想知道这个 SQL 是否是线程安全的。我只是使用下面的方式来模拟并发操作:
for ((i=0; i<100; i++))
do
mysql -uroot -p123456 test -e "update stock set quantity=quantity-1 where product_id = 1" >/dev/null &
done
然后检查最终数量是否为0。 我想知道这种方式是否正确?也就是说,它是否会像 100 个用户同时提交订单一样正确发送并发 SQL 命令?
最佳答案
这是一个很好的方法:
for ((i=0; i<100; i++)); do
mysql -uroot -p123456 test -e "update stock set quantity=quantity-1 where product_id = 1" >/dev/null &
done
wait
您需要在最后wait
使其在作业仍在运行时不退出。
关于mysql - 如何使用 shell 模拟并发 SQL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836976/