1

So i have multiple threads accessing this function to retrieve database information, is it thread safe?

vector<vector<string> > Database::query(const char* query)
{
    pthread_rwlock_wrlock(&mylock); //Write-lock
    ...
    vector<vector<string> > results;
    results.push...
    pthread_rwlock_unlock(&mylock); //Write-lock

    return results;
}

for editors -> sometimes 'fixing' > > to >> is not a good idea but thanks for the rest.

  • it's hard to be certain what you're asking. Using a local vector like this is thread-safe because it's being created on the stack. But we can't tell you if your function is thread safe. I can tell you that it will be inefficient because after building your vector of vectors of strings, you return a copy of it and not the original. – kfsone Jun 01 '13 at 22:53

3 Answers3

2

Since results is a local variable, it is in itself safe to use without locks, since there will be a unique copy per thread (it is on the stack, the contents of the vector dynamically allocated in some way, etc). So as long as your database is thread safe, you don't need any locks at all. If the DB is not threadsafe, you need to protect that, of course.

As noted in the other answer, if, for some reason, for example the creation of a string causes a throw bad_alloc;, you need to deal with the fallout of that, and make sure the lock is unlocked (unless you really wish to deadlock all other threads!)

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

Generally speaking, multiple threads can hold "read" locks. Only one thread can hold "write" lock. And no "read" locks might be held while there is a "write" lock.

It means that while mylock is held locked inside query method, no-one else can have it locked for either read or write, so it is thread-safe. You can read more about readers-writer lock here. Whether you need that mutex locked in there or not is another question.

The code is not exception-safe, however. You must employ RAII in order to unlock a mutex automatically, including on stack unwinding.

  • Any tutorials on the exception safety? or just a simple try{} catch() would do? – Бай Иван Jun 01 '13 at 22:48
  • @БайИван: Take a look at [this question](http://stackoverflow.com/questions/2635882/raii-tutorial-for-c). Try-catch will also do, but is generally more prone to errors and harder to write. –  Jun 01 '13 at 23:12
0

It is thread safe because results is created as a local variable, so only one thread will ever access it any instance of results within this method.

If you need a thread-safe vector for some other reason, see this answer on Threadsafe Vector Class for C++.

Community
  • 1
  • 1
Josh Milthorpe
  • 956
  • 1
  • 14
  • 27