qt - Why lock the QMutex at here? -
i'm reading qt's blocking fortune client example. there piece of code below:
mutex.lock(); qstring fortune; in >> fortune; emit newfortune(fortune); cond.wait(&mutex); servername = hostname; serverport = port; mutex.unlock();
i'm bit confused why lock mutex @ first line. because both fortune , in local variables. or emit should protected?
this code: http://doc.qt.io/qt-5/qtnetwork-blockingfortuneclient-fortunethread-cpp.html. entire project can found @ bottom of page.
seems lock placed in right place(i'd still place after in >> fortune;
). why might need lock
before emit?
emit happens in 1 thread while slot gets executed in different thread. following events might happen:
- t1 emits signal , gets suspended os.
- t2 gets time quant , having received signal starts executing slot(
showfortune
) - if
nextfortune == currentfortune
true thread'srequestnewfortune
gets executed in t2 context. requestnewfortune
trying lock mutex fails , gets suspended.- t1 gets resumed , proceed until
cond.wait
when releases mutex , gets suspended - since mutex released t2 gets resumed , executes code ends
cond.wakeone
- t1 gets resumed
wakeone
call , finishes code correctly.
what if didn't lock mutex before emit call? end step #4 executed
execute code ends
cond.wakeone
and wakeone
lost forever , when t1 cond.wait
not resumed since wakeone
call awaits lost.
Comments
Post a Comment