Click to See Complete Forum and Search --> : a semaphore question


dullboy
March 4th, 2004, 12:43 AM
Semaphore is usually used in guiding the access of, for example, a pool of connections. Now suppose we have 10 threads and 3 connections( they might be database connections or socket connections). In this situation, semaphore is a good candidate for protecting the access of connections. My question is how semaphore could prevent two threads to access the SAME connection? Say connection A, B, C. Thread 1 locks semaphore to access A, how could semaphore prevent thread 2 accessing A?

joscollin
March 4th, 2004, 03:05 AM
Hi,

You must start both threads and do wait thread2 while thread1 is accessing A. When it is finished accessing A release the waiting semaphore for thread2.

Andreas Masur
March 4th, 2004, 05:21 AM
[Moved thread]

Andreas Masur
March 4th, 2004, 05:21 AM
Synchronization (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization.asp)

dimm_coder
March 4th, 2004, 10:39 AM
Originally posted by dullboy
Say connection A, B, C. Thread 1 locks semaphore to access A, how could semaphore prevent thread 2 accessing A?

U should protect each connection with a mutex (this is an object as a semaphore but with a counter = 1). So, before working with some object (describing a connection in your case), any thread should lock a mutex for that object to gain an exclusive access.

For getting more details follow the link pointed out by Andreas or read another docs, describing synchronization aspects.

dullboy
March 4th, 2004, 12:12 PM
Originally posted by dimm_coder
U should protect each connection with a mutex (this is an object as a semaphore but with a counter = 1). So, before working with some object (describing a connection in your case), any thread should lock a mutex for that object to gain an exclusive access.

For getting more details follow the link pointed out by Andreas or read another docs, describing synchronization aspects.
Probably I didn't state my question well. Actually, I don't have problem with synchronization in general, but I do have problem with semaphore. Back to my case, semaphore may allow only at most 3 threads to access the pool of connections, but I just couldn't see how semaphore prevents two threads of them accessing the same connection. So do you mean if I use semaphore, I have to use mutex or critical section in the mean time?

Kheun
March 4th, 2004, 09:38 PM
Quite right. If you are limiting only a thread to access a shared resource at any one time, you can use either a mutex or critical section.