Is mutex needed to synchronize a simple flag between pthreads?

前端 未结 4 1819
栀梦
栀梦 2020-12-23 22:49

Let\'s imagine that I have a few worker threads such as follows:

while (1) {
    do_something();

    if (flag_isset())
        do_something_else();
}
         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 23:11

    For the example you have posted, case A is sufficient provided that ...

    1. Getting and setting the flag takes only one CPU instruction.
    2. do_something_else() is not dependent upon the flag being set during the execution of that routine.

    If getting and/or setting the flag takes more than one CPU instruction, then you must some form of locking.

    If do_something_else() is dependent upon the flag being set during the execution of that routine, then you must lock as in case C but the mutex must be locked before calling flag_isset().

    Hope this helps.

提交回复
热议问题