Sign in to follow this  
supagu

multithread problem

Recommended Posts

im trying to put support for multithreading in a my audio code. I'm doing this so i can seperate the streaming in to its own thread. now the problem i've come across is this: i have a method called Stop which acquires a semaphore reference and release once done the same class has an Update method which also acquires a semaphore and releases once done. The problem is this Update method calls Stop in some situations, so then i get a lock up. Would a Mutex fix this problem? if not, whats the recommended way to get around this? some sort of hidden last parameter to Stop which tells it no to acquire/release the semaphore?

Share this post


Link to post
Share on other sites
A mutex is simply a binary semaphore, where as semaphores in the usual sense can be incremented and decremented multiple times (that is to say, more than one thread can "lock" it at a time).

Do the Stop and Update methods both lock the same mutex? If so, as you said you could have Stop take a boolean parameter specifying whether or not to lock the mutex; Update would pass false since it would already have locked it. Or you could do something like this:


class Audio
{
private:

StopPrivate()
{
// don't lock/unlock mutex here, as it will already have been done
...
}

public:

Update()
{
LockMutex();
...
StopPrivate();
...
UnlockMutex();
}

Stop()
{
LockMutex();
StopPrivate();
UnlockMutex();
}
};


Share this post


Link to post
Share on other sites

StopImpl()
{
///
}

Stop()
{
lock();
StopImpl();
unlock();
}

Update()
{
lock();
if (stop) StopImpl();
unlock();
}


Use the scoped locking idiom, though.

Another solution would be to use a recursive mutex, though some would consider that a bad practice.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this