Martin Perry
Martin Perry

Reputation: 9527

C++ - synchronization of threads

I have this problem

Foo * foo = new Foo();

void A(){
  foo->a();
}

void B(){
  foo->b();
}

void C(){
  foo->reloadAll();
}

Once I enter method C and start reloading foo, I dont want to call A or B. However, A or B can be called together. In that case, I dont want to lock any threads.

How to synchronize this? I can use features provided by C++14. Currently, I am using active waiting (while loo with sleep) on atomic variable, but that is not ideal.

EDIT: Calling A, B, or C in threads is driven by GUI (written in other language), so I have no real threads within C++ app.

Upvotes: 1

Views: 128

Answers (3)

centralcmd
centralcmd

Reputation: 21524

What about using two unique locks, one for a and one for b. Lock when a/b starts and unlock when a/b ends, respectively, c locks/unlocks both?

Upvotes: 0

Jeka
Jeka

Reputation: 1384

I think best option is shared_mutex, method C should use unique lock, but A and B use shared lock, check if it available for you.

Also you can use try_lock_shared to return from A and B if C is locked, instead of waiting.

Upvotes: 3

Avishai Y
Avishai Y

Reputation: 123

Looks like a readers-writer problem. A and B needs to lock as readers, and C as a writer. Look here: Reader/Writer Locks in C++

Upvotes: 4

Related Questions