tags:

views:

41

answers:

3

I have something similar to an online chat client. When one user sends a message it will be stored in a MySQL database table with id=currentID+1. I have another client long polling and waiting for message 'id=currentID+1'.

After this exchange, that row is never used again.

Do I need a lock in this case? The thing I'm worried about is that the reading PHP side will be able to see the row and read its values before the writing PHP side finishes creating the row.

A: 

MySQL won't make the row available until it's done reading (it automatically acquires a table lock in the case of MyISAM, or a row lock in the case of INNODB. So no, you should be ok so long as you're only inserting the row (and not later calling updates on it, etc)...

ircmaxell
So let me get this straight. An insert operation always implicitly locks the table(ISAM) or row (innoDB)?
teehoo
Correct. InnoDB can be a little more complicated, in that you can have a transaction where it's locked until you issue the commit command. But for general usage (without starting a transaction in InnoDB) that's correct...
ircmaxell
A: 

Writes in MySQL are atomic. Other queries cannot "see" the row until it is completely written, assuming you're using a single INSERT statement to do this.

ryeguy
You mean inserts in MySQL are atomic right? If writes were atomic I don't think we'd need locks.
teehoo
@teehoo: No, I meant writes. Locks are used when you want to do *multiple* writes atomically. For example, deducting the balance from one account and putting it in another would need to be done in a transaction. But if you do a single insert or an update statement, no one can see it until it's finished (ie, if you were updating 5 columns, they wouldn't see it in a state where only 3 were updated).
ryeguy
A: 

the new row will only be seen by the select query after its inserted.

inserts are atomic

and yes myisam imploys table level locking, while innodb imploys row level locking.

and set of statements in a transaction are considered atmoic, there effect is not visible to any read until the transaction is committed, u can do a select shared to see uncommitted data.

ovais.tariq