我正在編寫一個程序,在該程序中,我需要確保調用某個特定函數不會一次在多個線程中執行。線程同步:確保函數按順序調用
在這裏,我寫了一些簡化的僞代碼,完全在我的真實程序中做了什麼。
mutex _enqueue_mutex;
mutex _action_mutex;
queue _queue;
bool _executing_queue;
// called in multiple threads, possibly simultaneously
do_action() {
_enqueue_mutex.lock()
object o;
_queue.enqueue(o);
_enqueue_mutex.unlock();
execute_queue();
}
execute_queue() {
if (!executing_queue) {
_executing_queue = true;
enqueue_mutex.lock();
bool is_empty = _queue.isEmpty();
_enqueue_mutex.lock();
while (!is_empty) {
_action_mutex.lock();
_enqueue_mutex.lock();
object o = _queue.dequeue();
is_empty = _queue.isEmpty();
_enqueue_mutex.unlock();
// callback is called when "o" is done being used by "do_stuff_to_object_with_callback" also, this function doesn't block, it is executed on its own thread (hence the need for the callback to know when it's done)
do_stuff_to_object_with_callback(o, &some_callback);
}
_executing_queue = false;
}
}
some_callback() {
_action_mutex.unlock();
}
從本質上講,這個想法是,_action_mutex
鎖定在while循環(我應該說,lock
被假定爲阻塞,直到它可以再次鎖定),並預計將在解鎖時完成回調被稱爲(上述代碼中的some_callback
)。
雖然這似乎並不奏效。如果do_action
被同時調用多次,會發生什麼情況,程序會被鎖定。我認爲這可能與while循環同時執行超過一次有關,但我不知道這是怎麼回事。我的方法有什麼問題嗎?有更好的方法嗎?
感謝
oops ...我在代碼中有這個...我在輸入僞代碼時錯過了它。我會更新我的問題。謝謝 –
調試程序的第一步是添加一些'printf'語句。 – rwong
好的,請不要以爲我這樣說不禮貌,但我在嘗試尋求幫助之前嘗試自行解決問題。我知道while循環因此嘗試多次執行(見問題)。此外,鎖定互斥檢查isEmpty並不能解決問題。 –