title: MySQL: How to lock tables and start a transaction?
body: <p><em>TL;DR - MySQL doesn't let you lock a table and use a transaction at the same time.  Is there any way around this?</em></p>
  
  <p>I have a MySQL table I am using to cache some data from a (slow) external system.  The data is used to display web pages (written in PHP.)  Every once in a while, when the cached data is deemed too old, one of the web connections should trigger an update of the cached data.</p>
  
  <p>There are three issues I have to deal with:</p>
  
  <ul>
  <li>Other clients will try to read the cache data while I am updating it</li>
  <li>Multiple clients may decide the cache data is too old and try to update it at the same time</li>
  <li>The PHP instance doing the work may be terminated unexpectedly at any time, and the data should not be corrupted</li>
  </ul>
  
  <p>I can solve the first and last issues by using a transaction, so clients will be able to read the old data until the transaction is committed, when they will immediately see the new data.  Any problems will simply cause the transaction to be rolled back.</p>
  
  <p>I can solve the second problem by locking the tables, so that only one process gets a chance to perform the update.  By the time any other processes get the lock they will realise they have been beaten to the punch and don't need to update anything.</p>
  
  <p>This means I need to both lock the table <em>and</em> start a transaction.  According to the MySQL manual, <a href="http://dev.mysql.com/doc/refman/5.6/en/lock-tables-and-transactions.html" rel="noreferrer">this is not possible</a>.  Starting a transaction releases the locks, and locking a table commits any active transaction.</p>
  
  <p>Is there a way around this, or is there another way entirely to achieve my goal?</p>