Click to See Complete Forum and Search --> : Semaphore not releasing


freax
October 5th, 2005, 04:44 PM
I am making an application which requires sending data from a thread to another thread. For that, I am sending a commom variable into all threads. For synchronization, I am using semaphores. However, a simple trial isn't working. The ReleaseSemaphore isn't working. Am pasting the code here, please help!


#include"stdafx.h"
#include<iostream>

using namespace std;

UINT
func(LPVOID);

int main(int argc,char **argv) {
int n,m;

HANDLE h,h1;
SECURITY_ATTRIBUTES s;
s.nLength=sizeof(SECURITY_ATTRIBUTES);
s.lpSecurityDescriptor=0;
s.bInheritHandle=true;

h=CreateSemaphore(&s,0,1,"sem1");
h1=CreateSemaphore(&s,1,1,"sem2");
cout<<"I am here!!!\n";

AfxBeginThread(func,(LPVOID)&n);
// AfxBeginThread(func,(LPVOID)&m);

cout<<"Thread created!!!";

WaitForSingleObject(h,INFINITE);

cout<<"Value of n is: "<<n<<endl;
return 1;
}

UINT
func(LPVOID p) {
int *i=(int*)p;
HANDLE h,h1;

h=OpenSemaphore(SYNCHRONIZE,true,"sem1");
h1=OpenSemaphore(SYNCHRONIZE,true,"sem2");


cout<<"Am in thread!!!\n";

WaitForSingleObject(h1,INFINITE);
//WaitForSingleObject(h1,INFINITE);

cout<<"Enter number: ";
cin>>*i;

ReleaseSemaphore(h1,1,NULL);
//For trial only
WaitForSingleObject(h1,INFINITE);
cout<<"Enter another number: ";
cin>>*i;

ReleaseSemaphore(h1,1,NULL);

ReleaseSemaphore(h,1,NULL);
cout<<"This is done!\n";
return 1;
}

wildfrog
October 5th, 2005, 05:49 PM
Your thread need both SYNCHRONIZE and SEMAPHORE_MODIFY_STATE access to the opened semaphores.


h=OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, true,"sem1");
h1=OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, true,"sem2");

You should also check the result of your function calls. Both when creating, opening, waiting and releasing...

- petter

Marc G
October 6th, 2005, 04:33 AM
[ moved thread ]

freax
October 6th, 2005, 09:34 AM
Thanks a lot! Working absolutely fine now.