mutex's ownership

Hi everybody

How can I hand over the ownership of a created mutex in the main function to other thread?
if the mutex handle is global any one can use that handle.
the mutex handle is global

but I need that a function owns it the first time and when this function has done its work, release the mutex and the main function (where the mutex was created)can take it

help me please!
you mean the main function use it first and then the thread should use it?

but who is creating this mutex??

if you can explain the scenario then i can tell something.
I have to threads: one in the main function, one in a separate function

I have a global mutex who is created in the main function (mutex_req=CreateMutex(NULL, FALSE, "my_mutex") the second parameter set to FALSE means that the main thread doesn't take it after creating.

So the second thread takes it and works, at the end, releases it and then the main function thread should take it and works but it does'n work. The main thread stays at this point in the WaitForSingleObject(mutex_req)

I show you some code:

#include...
....
HANDLE mutex_req;
...
DWORD WINAPI tcpserver()
{ mutex_req=CreateMutex(NULL,TRUE, "req_mutx");
bool run_tcpserver=TRUE;
if (listen(socketInTCP,1) == SOCKET_ERROR)
printf("Server: listen(): Error listening on socket %ld.\n", WSAGetLastError());
else
{
cout << " TCP-Server Start \n" << endl;
}

char recvbuf[1500] = "";
int bytesRecv = SOCKET_ERROR;
int control=1;
while (1)
{ SOCKET AcceptSocket;
AcceptSocket = accept(socketInTCP, NULL, NULL);
if (AcceptSocket == INVALID_SOCKET)
{
printf("Server: WSA:\n");

}
else
{
printf("Server: Client Connected!\n");
while(run_tcpserver)
{ bytesRecv = recv(AcceptSocket, recvbuf, sizeof(recvbuf), 0);
if (bytesRecv > 0)//Client hat Verbindung beendet
{WaitForSingleObject(mutex_req, INFINITE);
control=1;
ofstream outfile(outputfile, ios::app | ios::binary | ios::trunc);//open
cout <<"incoming Rx Dump Data ... \n";
}
outfile.write (recvbuf, bytesRecv);
outfile.close();
memset(recvbuf,0,sizeof(recvbuf));
}
else
{if(control==1;
ReleaseMutex(mutex_req);
control++;
}
}

//socketInTCP=AcceptSocket;

}
}
return 0;
}

int main()
{
thread2 = CreateThread(0, 0,(LPTHREAD_START_ROUTINE) tcpserver,NULL,0,&threadID2);
....
WaitForSingleObject(mutex_req,INFINITE);//when first dump ready, we request the next
length = createMessage2(packet);
initiateRxDump(packet);
ReleaseMutex(mutex_req);
......
}
Topic archived. No new replies allowed.