Is mutex needed to synchronize a simple flag between pthreads?

前端 未结 4 1807
栀梦
栀梦 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:17

    Assigning incoming job to worker threads requires no locking. Typical example is webserver, where the request is catched by a main thread, and this main thread selects a worker. I'm trying explain it with some pesudo code.

    main task {
    
      // do forever
      while (true)
    
        // wait for job
        while (x != null) {
          sleep(some);
          x = grabTheJob(); 
        }
    
        // select worker
        bool found = false;
        for (n = 0; n < NUM_OF_WORKERS; n++)
         if (workerList[n].getFlag() != AVAILABLE) continue;
         workerList[n].setJob(x);
         workerList[n].setFlag(DO_IT_PLS);
         found = true;
        }
    
        if (!found) panic("no free worker task! ouch!");
    
      } // while forever
    } // main task
    
    
    worker task {
    
      while (true) {
        while (getFlag() != DO_IT_PLS) sleep(some);
        setFlag(BUSY_DOING_THE_TASK);
    
        /// do it really
    
        setFlag(AVAILABLE);
    
      } // while forever 
    } // worker task
    

    So, if there are one flag, which one party sets is to A and another to B and C (the main task sets it to DO_IT_PLS, and the worker sets it to BUSY and AVAILABLE), there is no confilct. Play it with "real-life" example, say, when the teacher is giving different tasks to students. The teacher selects a student, gives him/her a task. Then, the teacher looks for next available student. When a student is ready, he/she gets back to the pool of available students.

    UPDATE: just clarify, there are only one main() thread and several - configurable number of - worker threads. As main() runs only one instance, there is no need to sync the selection and launc of the workers.

提交回复
热议问题