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:

  1. t1 emits signal , gets suspended os.
  2. t2 gets time quant , having received signal starts executing slot(showfortune)
  3. if nextfortune == currentfortune true thread's requestnewfortune gets executed in t2 context.
  4. requestnewfortune trying lock mutex fails , gets suspended.
  5. t1 gets resumed , proceed until cond.wait when releases mutex , gets suspended
  6. since mutex released t2 gets resumed , executes code ends cond.wakeone
  7. 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

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -