mutex problem

This is a discussion on mutex problem within the C++ Programming forums, part of the General Programming Boards category; Hi everybody, I have a mutex problem between two threads (one thread in the main function and the other in ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    35

    mutex problem

    Hi everybody,

    I have a mutex problem between two threads (one thread in the main function and the other in a thread function). I have a global mutex who create in the thread function (CreateMutex) because I want that this thread owns the mutex first. When mutex is released the main function get it and works. The problem is that the main function thread is waiting for the thread forever although the other thread have already released.

    have you any ideas?

    Thank you

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    You probably aren't releasing it properly. Post the relevant code.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    Hi again,

    some code:

    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);	
    				 ofstream outfile(outputfile, ios::app | ios::binary | ios::trunc);//open
    					 printf("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);
     ......
    }
    Thank you for your help

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Ok.

    1) You need to create the mutex in the main thread. Why? Because main may reach 'WaitForSingleObject(mutex_req,INFINITE);' before the thread even begins executing!
    2) Normally, you should pair WaitForSingleObject/ReleaseMutex in the same scope. That certainly isn't always the case, but it is much more reliable. Don't control them separately, if possible.
    3) It would probably be a good idea to have the thread 'yield' at some point to ensure that the main thread gets to use the mutex. Something like:

    Code:
    	bytesRecv = recv(AcceptSocket, recvbuf, sizeof(recvbuf), 0);
    	if (bytesRecv > 0)//Client hat Verbindung beendet
    	{
    		WaitForSingleObject(mutex_req, INFINITE);	
    		ofstream outfile(outputfile, ios::app | ios::binary | ios::trunc);//open
    		printf("incoming Rx Dump Data ... \n");
    		outfile.write (recvbuf, bytesRecv);
    		outfile.close();
    		memset(recvbuf,0,sizeof(recvbuf));
    		ReleaseMutex(mutex_req);
    		Sleep(0);
    	}
    Also:

    - Make sure the libraries you're using are thread safe. You might be surprised to find how many are not!
    - It really doesn't make sense to use iostreams and printf in the same program. Pick one.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    Hi again,

    Thank you for the answer, but if I create the mutex in the main function this thread takes the mutex first and I don't want this. The mutex must be taken by the thread funcion tcp_server AT FIRST and when this thread is ready, the main function must take the mutex and works...

    So, if I create the mutex in the first function it doesn't work properly.

    How can I do to give the mutex to the thread function the first time?

  6. #6
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    So, my question is

    How can I hand over the ownership of a created mutex in the main function to other thread?

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    if I create the mutex in the main function this thread takes the mutex first
    I don't see why. A newly created mutex is not held by anyone.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    When you create a mutex with the second argument BOOL bInitialOwner, TRUE, the ownership goes to the thread who created it. I tried to use it with FALSE but it doesn't work. The thread takes over the ownership first I need that other thread first works (other thread takes the mutex first)

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Well, you could just release the mutex immediately after creating it.

    The fact is, synchronization primitives must be created before the threads they're supposed to synchronize. Everything else is far too error-prone.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    Well, it's possible but my problem now is that the thread in the main function stays at the point "WaitForSingleObject()" forever although the other thread have already released the mutex...

  11. #11
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Hmm ... at the moment, I can't see how your core server loop can even compile.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  12. #12
    Registered User
    Join Date
    Mar 2009
    Posts
    35
    shall I show you some code?

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    If the code of post #3 is out of date, then yes.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Another thing I noticed was that you're using a named mutex. That really ins't necessary, and in fact, could create problems since the mutex could be opened by another process and manipulated...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  15. #15
    Registered User
    Join Date
    Jun 2005
    Posts
    6,298
    Quote Originally Posted by radeberger View Post
    Thank you for the answer, but if I create the mutex in the main function this thread takes the mutex first and I don't want this. The mutex must be taken by the thread funcion tcp_server AT FIRST and when this thread is ready, the main function must take the mutex and works...

    So, if I create the mutex in the first function it doesn't work properly.

    How can I do to give the mutex to the thread function the first time?
    You actually have a fundamental problem with your design.

    My guess is that you have some "startup code" in your thread function, and your main thread will bomb out if that startup code hasn't been run. That's a fatal design mistake: your main thread needs to assume the startup code has not been run, and wait until it has. For example, if that startup code creates a file that is needed in the main thread, the main thread needs to grab the mutex, check if the file exists, and - if it doesn't - release the mutex and try again (preferably with a small Sleep() to stop thrashing the CPU). In other words, it needs to wait until the worker thread has set things up.

    It's not strictly necessary that a mutex be created by the main thread. That is simply common practice, because the main thread usually orchestrates creation of other threads, so it is simpler if it also orchestrates creation of synchronisation mechanisms (mutexes, etc).
    Right 98% of the time, and don't care about the other 3%.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 10:22 AM
  2. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  3. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  4. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  5. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 05:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21