![]() |
| | #1 |
| Registered User Join Date: Sep 2006
Posts: 6
| clueless about the semaphore object that can coordinate the access of a resource... my resource is an array of strings.. my producers will put strings into the array, my consumers will retrieve one string at a time then delete that one string from the array once they got it. i would like the consumers and producers to take turns in accessing the string array. eg.. only one consumer can be accessing the string array or only one producer can be adding into the string array at any given time. anyways, right now i am thinking of this strategy ...(after reading some pseudocodes and producer/consumer semaphore solutions online) Code: HANDLE hsem1; // gate to restrict access to string array.
HANDLE hsem2; // signal when string array full
HANDLE hsem3; // signal when string array empty
DWORD dwProdWait;
DWORD dwConsWait;
TCHAR sem1Name[] = TEXT("String array resource");
// create the gate for restricting access to the string array
// initial count 0 to allow time for setting up string array
hsem1 = CreateSemaphore(NULL, 0, 1, sem1Name);
// increment semaphore so that string array can now be accessed
ReleaseSemaphore(hSemaphore, 1, NULL);
// producer try to enter the gate
dwProdWait = WaitForSingleObject(hsem1, 0L);
switch (dwProdWait)
{
case WAIT_OBJECT_0: // Semaphore object signaled
break;
case WAIT_TIMEOUT: // Semaphore object non-signaled.
break;
}
i am dumbfounded right now.. how i can make
the producer wait on the boxempty to be nonsignaled
and how i can make the consumer wait
for boxfull to be nonsignaled..
is this even a valid strategy right now ? please help thanks.
|
| y_cant_i_C is offline | |
| | #2 |
| Yes, my avatar is stolen Join Date: Dec 2002
Posts: 2,544
| If you only want one thread at a time to access a resource, you can use a critical section (simplest), event, mutex or a semaphore. To wait on a semaphore just use a non-zero timeout. You can't wait for an object to be non-signalled, only signalled. A semphore is signalled when its count is not zero. Calling WaitForSingleObject with a semaphore decreases its count by one. Code: WaitForSingleObject(hsem1, INFINITE); // Access resource here... ReleaseSemaphore(hsem1, 1, NULL); |
| anonytmouse is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| using this as synchronization object | George2 | C# Programming | 0 | 03-22-2008 07:49 AM |
| circular doubly linked list help | gunnerz | C++ Programming | 5 | 04-28-2007 08:38 PM |
| Semaphore Question | azamsharp1 | C Programming | 4 | 10-30-2005 09:01 AM |
| Question on l-values. | Hulag | C++ Programming | 6 | 10-13-2005 04:33 PM |
| A question about constructors... | Wolve | C++ Programming | 9 | 05-04-2005 04:24 PM |