Thread resource sharing

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-03-23T14:53:01Z Indexed on 2010/03/23 15:03 UTC
Read the original article Hit count: 572

I'm struggling with multi-threaded programming...

I have an application that talks to an external device via a CAN to USB module. I've got the application talking on the CAN bus just fine, but there is a requirement for the application to transmit a "heartbeat" message every second.

This sounds like a perfect time to use threads, so I created a thread that wakes up every second and sends the heartbeat. The problem I'm having is sharing the CAN bus interface. The heartbeat must only be sent when the bus is idle. How do I share the resource?

Here is pseudo code showing what I have so far:

TMainThread
{
    Init:
        CanBusApi =new TCanBusApi;
        MutexMain =CreateMutex( "CanBusApiMutexName" );

        HeartbeatThread =new THeartbeatThread( CanBusApi );

    Execution:
        WaitForSingleObject( MutexMain );
        CanBusApi->DoSomething();
        ReleaseMutex( MutexMain );
}

THeartbeatThread( CanBusApi )
{
    Init:
        MutexHeart =CreateMutex( "CanBusApiMutexName" );

    Execution:
        Sleep( 1000 );
        WaitForSingleObject( MutexHeart );
        CanBusApi->DoHeartBeat();
        ReleaseMutex( MutexHeart );
}

The problem I'm seeing is that when DoHeartBeat is called, it causes the main thread to block while waiting for MutexMain as expected, but DoHeartBeat also stops. DoHeartBeat doesn't complete until after WaitForSingleObject(MutexMain) times out in failure.

Does DoHeartBeat execute in the context of the MainThread or HeartBeatThread? It seems to be executing in MainThread.

What am I doing wrong? Is there a better way?

Thanks, David

© Stack Overflow or respective owner

Related posts about threads

Related posts about mutex