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;
}
#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;
}