O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required