开发者

mysql - How to commit after multiple inserts

I have 2 cron processes running in parallel.

Process 1 does inserts and process 2 reads these inserts.

The problem I have is process 1 needs to insert multiple rows before process 2 can read them.

For example, 1. Process 1 needs to insert 10 rows

  1. Process 1 inserts 3 rows

  2. Process 2 reads these 3 rows

  3. Process 1 inserts rows 4..10

  4. Process 2 reads rows 4..10

What I needs is

  1. Process 1 row inserts 1..10

  2. Process 2 reads rows 1..10

A) Do I lock the table for the inserts in process 1?

B) Do I do a begin transaction, do inserts, and then commit?

开发者_开发问答

If the table is locked will other session what for the unlock or will the other sessions get a lock error/warning?


Don't lock the table. Use a transaction. Transactions are atomic.


If you need to block process 2 until process 1 is complete, you should, as you suggested, lock the tables in question.

If you are inserted all 10 rows in a single query, you can rely on MyISAM table locking, however, if you are inserting using separate queries or are using InnoDB, you will want to explicitly lock the tables using [LOCK TABLES .. WRITE] (http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html) in process 1 and release the locks when you're finished.

Process 2 will then graciously wait for the write lock to be released before reading from the table.

It's very important here to ensure that the server receives the queries in process 1 first, so you may wish to use some magic there.

You could wrap the inserts inside of a transaction if you want to ensure that all of the inserts are atomically added, but you will still need to lock the table to solve the concurrency issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜