Advertisement
Guest User

Untitled

a guest
May 30th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. /* Because bitset comprises 3 operations:
  2. * 1. Read array[bitset_index] into 'temp'
  3. * 2. Set bit (bit_index) on 'temp'
  4. * 3. Write 'temp' into array[bitset_index]
  5. * A thread running bitset can be preempted before it can write 'temp', during
  6. * which time another thread has written 'array[bitset_index]', and 'temp' does
  7. * not include the changes made by that thread. Thus, the preempted thread
  8. * overwrites the changes made by the other thread when it executes step 3.
  9. *
  10. * To avoid this, I use the GCC extension '__sync_bool_compare_and_swap' which
  11. * does an atomic compare and swap with 'oldval' (the initial value of
  12. * array[bitset_index]) and 'newval' ('oldval' with the relevant bit set on it)
  13. * and returns true if the operation succeeded and false if it doesn't.
  14. *
  15. * Thus, I just use it in a do while loop and keep trying the operation until
  16. * it succeeds.
  17. */
  18. void bitset(unsigned char * array, int index){
  19. int newval;
  20. int oldval;
  21. int bitset_index = index / BITS_PER_INDEX;
  22. int bit_index = index % BITS_PER_INDEX;
  23. do{
  24. oldval = array[bitset_index];
  25. newval = oldval | (1 << (bit_index));
  26. }while(!__sync_bool_compare_and_swap(&array[bitset_index], oldval, newval));
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement