Q:

Does putting all of your code between mutex_lock and mutex_unlock render multithreaded(ness) meaningless

Say I'm writing a multi threaded server which takes in different database queries from a client, looks up the database and gives back results.
If I put ALL of my server code to receive the client query, database lookup and response to client within mutex_lock and mutex_unlock, doesn't it mean that a new thread has to wait for the entire code to be executed? So isn't this similar to just running a for-loop for all the client requests for a single-threaded server?
I feel the only difference would be that a for loop executes from 1 to 100, say in sequence, but for a loop like below, the order of threads cannot be predicted
pthread_t th[100];
for(i=0;i<100;i++)
{
 pthread_create(&th[i], NULL, fun, NULL);
}

Am I right in saying so?
Please advise.
Thanks.

A:

In the book C++ Concurrency in Action, Anthony Williams says there are two main reasons to use concurrency:

performance
separation of concerns

optional reason

because I want to

You are right, creating 100 threads and then serializing them all on one mutex makes multithreaded-ness meaningless, it actually hurts #1 and does nothing for #2.  It will burden the operating system with 100 threads, only one of which can run at a time because the rest will be blocked/serialized waiting on the mutex, it will incur unnecessary context switch overhead, and the overhead of the mutex itself.
A server servicing database requests should be multi-threaded, for both #1 and #2.
New threads could be created when a new requests arrive. The alternative is to use a thread pool.  One thread accepts requests, and creates a new thread (or enqueues to the thread pool) to handle the request then goes back to accept another request.  See this answer for more details.  Whether you need to serialize on a mutex or not to access the database depends on the database, most allow concurrent connections, see this answer for MySql

