Lock Granularity

Most reasonable implementations of a Web server will make some rudimentary statistics available to the Web master. For example, our implementation kept track of the number of HTTP and HTTPS (SSL) requests:

class HTStats {
    int httpReqs;
    int sslReqs;
    pthread_mutex_t lock;
    ...
};

Since multiple threads may try to manipulate the statistics concurrently, we had to protect it with a mutex lock:

void HTStats::addHttpReq()// Increment the counter for HTTP requests.
{
    pthread_mutex_lock(&lock);
    httpReqs++;
    pthread_mutex_unlock(&lock);
}

void HTStats::addSslReq()// Increment the counter for HTTPS requests.
{
    pthread_mutex_lock(&lock);
    sslReqs++;
    pthread_mutex_unlock(&lock);
}

As you can tell from this code, the HTStats class uses a ...

Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.