I have functions lock(), unlock(), query1(), query2() and query3(). The query functions just run some query on a database and can be considered r/w access to it. They do not lock. My system is multithreaded.
The functionality I want is: If lock() is called from thread p1, only queries from thread p1 will run and queries from all other threads wait for unlock. How do I do this?
I'm using pthreads from C. To do this, the thread must know that it holds the lock. But pthreads doesn't have such a function.
Is the design wrong??
EDIT:
Function1(){
lock();
query1();
query2();
doQuery3();
unlock();
}
doQuery3(){
lock();
query3();
unlock();
}
The behaviour I want with lock() is that if the thread already is holding that lock, it should not wait on the lock. It should just run. The thing is my lock() function actually starts a transaction. I want to run a bunch of stuff in the transaction. And unlock() ends the transaction. I want to be able to chain queries. One workaround is to call query3() in Function1() instead of doQuery3(); That would mean for every function there are two versions, one with the locking and one vanilla query()
Again, these lock and unlock functions may or maynot be mutex locks. I tried implementing it with pthread mutex, but couldn't. Because a pthread_mutex_lock on the same thread blocks! Any cool tricks??