[so] Wait for zero
    Razvan Deaconescu 
    razvand at cs.pub.ro
       
    Wed Apr  9 00:02:02 EEST 2008
    
    
  
On Tue, 2008-04-08 at 13:21 -0700, Alexandru Marinescu wrote:
> In linux in momentul in care se face 
> struct sembuf op = {0, 0, 0};
> semop(sem, &op, 1);
> 
> Un proces va astepta ca primul semafor din multimea de semafoare
> descrise de sem sa ajunga la valoarea 0.
> 
> Cum pot face in Windows o blocare a unui proces pe un semafor pana
> cand acesta ajunge la zero?
Direct nu ai cum.
Poti folosi urmatoarea smecherie:
---
struct ZeroSemaphore {
	HANDLE hSem;
	HANDLE mutex;
	DWORD count;
	DWORD initVal;
};
struct ZeroSemaphore * CreateZeroSemaphore(key, initVal, maxVal)
{
	struct ZeroSemaphore *zs = malloc(sizeof(*zs));
	zs->hSem = CreateSemaphore(key, 0, maxVal);
	zs->count = initVal;
	zs->initVal = initVal;
	zs->mutex = CreateMutex/Semaphore ...
}
BOOL WaitForZero(struct ZeroSemaphore *zs)
{
	WaitForSingleObject(mutex);
	count--;
	if (count == 0)
		ReleaseSemaphore(zs->sem, initVal, NULL);
	ReleaseMutex/Semaphore(mutex);
	WaitForSingleObject(zs->sem);
}
BOOL Destroy/CloseZeroSemaphore(struct ZeroSemaphore *zs)
{
  ...
}
---
Greselile din cod sunt vina clientului de mail, nu a autorului :-P. Dupa
cum vezi, poti folosi o constructie asemanatoarea celei de implementare
a unei bariere pentru emularea operatiei wait-for-zero (inexistenta pe
Windows). De fapt aceasta este si una din utilizarile importante ale
operatiei: implementarea facila a unei bariere.
Nota: Eu stiu ca nu exista nativ operatia wait-for-zero pe Windows. Din
ce am gugaluit nu am gasit nici o informatie in acest sens. Daca exista,
imi cer scuze. Oricum, codul de mai sus are rezultate identice cu o
operatie wait-for-zero cu dezavantajul pierderii transparentei.
Razvan
-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.
    
    
More information about the so
mailing list