Finding the next in round-robin scheduling by bit twiddling

前端 未结 9 1712
日久生厌
日久生厌 2021-02-02 02:46

Consider the following problem. You have a bit-string that represents the current scheduled slave in one-hot encoding. For example, \"00000100\" (with the leftmost bit being #7

9条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 03:15

    This should do what you want:

    number_of_tasks= 
    next_mask= current | (current - 1);
    next_barrel= next | (next << number_of_tasks);
    next_barrel&= ~number_of_tasks;
    next_barrel&= -next_barrel;
    next_barrel|= next_barrel >> number_of_tasks;
    next_task_mask= next_barrel & -next_barrel;
    

    Basically, duplicate the bits of the next task mask, mask off the bits we don't want to consider, find the lowest set bit, fold the high bits back in, then take the lowest bit set. This runs in constant time.

    Edit: Updating to take into account current == 00010000 and next_mask == 00111000

提交回复
热议问题