Project

General

Profile

Calling WApplication methods from another thread

Added by Alexander Morozov about 10 years ago

Hi all,

I need to call methods of my WApplication`s descendants from main thread (from which WServer is started).

If I use WServer::post method can be really called in another order.

So I have to use UpdateLock:

for(auto app : apps_list) {

WApplication::UpdateLock lock(app);

if(lock) app->notify(message);

}

My application class derived from WApplication adds WApplication* to apps_list in constructor and remove it in desctructor.

Different threads using apps_list can damage it.

So I need to protect it with my mutex.

If I do so:

boost::lock_guardboost::mutex lock(mutex);

for(auto app : apps_list) {

WApplication::UpdateLock lock(app);

if(lock) app->notify(message);

}

I can get deadlock because constructor and destructor get UpdateLock implicitly so a program get locks in different order.

I try to avoid deadlock such way:

apps_list_t apps_list_copy;

{

boost::lock_guardboost::mutex lock(mutex);

apps_list_copy = apps_list;

}

for(auto app : apps_list_copy) {

WApplication::UpdateLock lock(app);

if(lock) app->notify(message);

}

But in this case an application can be removed from apps_list after creating a copy and releasing a lock.

// You should prevent the application from being deleted somehow,

// before you could grab the application lock.

http://www.webtoolkit.eu/wt/doc/reference/html/classWt_1_1WApplication.html#ad9631ca64e68d30d40cb49c90e55223d

How could I solve my problem?


Replies (1)

RE: Calling WApplication methods from another thread - Added by Alexander Morozov about 10 years ago

I can get deadlock because constructor and destructor get UpdateLock implicitly so a program get locks in different order.

I was not right here.

Getting UpdateLock by constructor is not a problem because other thread can not use it before adding app in apps_list by constructor.

After destructor get UpdateLock it will not be taken in another thread:

WApplication::UpdateLock lock(app);
if(lock) <- lock is false here
    (1-1/1)