简体   繁体   English

具有多个线程的事务和锁定

[英]Transaction and Locking with multiple threads

Hi All following is the problem scenario: 大家好,以下是问题情况:

I am using MYSQL (Innodb engine), one of my application(C++/MYSQLCAPI) is doing following operation : 我正在使用MYSQL(Innodb引擎),我的一个应用程序(C ++ / MYSQLCAPI)正在执行以下操作:

START TRANSACTION 开始交易

truncate my_table 截断my_table

load Data infile into table my_table. 将数据文件加载到表my_table中。

if both the above command [truncate and load ] are successful then COMMIT 如果以上命令[truncate和load]均成功,则COMMIT

else ROLLBACK 否则回滚

now another application(C++/MYSQLCAPI) which is reading this table in every second by following command. 现在是另一个应用程序(C ++ / MYSQLCAPI),它正在通过以下命令每秒读取此表。

select * from my_table 从my_table中选择*

ERROR: in this read attempt sometime it gets 0 data , what could be the reason for this ? 错误:在此读取尝试中有时它获得0数据,这可能是什么原因?

You're seeing an empty table since truncate table has an implicit commit . 由于截断表具有隐式提交,因此您会看到一个空表。 If you need to change the entire table in a transaction you can use delete then insert, or try the rename solution presented in this answer 如果需要在事务中更改整个表,则可以使用Delete然后插入,或尝试使用此答案中提供的重命名解决方案

CREATE TABLE new LIKE real;
load `new` by whatever means
if something went wrong, don't do the next two steps.
RENAME TABLE real TO old, new TO real;
DROP TABLE old;

This avoids the problem you mentioned, plus lots of other problems. 这样可以避免您提到的问题以及其他许多问题。 In particular, it needs no special transaction handling; 特别是,它不需要特殊的事务处理; the RENAME is atomic and very fast. RENAME是原子的并且非常快。

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

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