structrwlock{volatileuint32_tstate;};staticvoid__rwlock_init(structrwlock*lock){lock->state=0;}staticvoid__read_lock(structrwlock*lock){unsignedintnew_state;unsignedintexpected;do{expected=lock->state&0xffff;/* I expect no write lock */new_state=expected+1;/* Add me as reader */}while(!__sync_bool_compare_and_swap(&(lock->state),expected,new_state));}staticvoid__read_unlock(structrwlock*lock){unsignedintnew_state;unsignedintexpected;do{expected=lock->state;/* I expect a write lock and other readers */new_state=expected-1;/* Drop me as reader */}while(!__sync_bool_compare_and_swap(&(lock->state),expected,new_state));}staticvoid__write_lock(structrwlock*lock){unsignedintnew_state;unsignedintexpected;do{expected=lock->state&0xffff;/* I expect some 0+ readers */new_state=(1<<16)|expected;/* I want to lock the other writers */}while(!__sync_bool_compare_and_swap(&(lock->state),expected,new_state));/* Wait pending reads */while((lock->state&0xffff)>0)/* cpu_relax(); */;}staticvoid__write_unlock(structrwlock*lock){unsignedintnew_state;unsignedintexpected;do{expected=1<<16;/* I expect to be the only writer */new_state=0;/* reset: no writers/no readers */}while(!__sync_bool_compare_and_swap(&(lock->state),expected,new_state));}