In reply to your first comment, yes it does involve an SQL transaction. It connects to the database, prepares a query, executes it, fetches rows in turn in a while loop, and then at the end disconnects and finishes. You mention a lock, I was not aware about any form of lock (as I said I am a complete novice).
So, could it be that because the database connection and query is closed only at the end of the file, the next process needs to wait until the previous query is completed..
So with that knowledge, would it speed things up to do the query at the start of the script, load the response into an array, close the query and connection and then loop through the array?