我的实现是Peterson过滤器锁的简单书面实现。 我对C ++有非常基本的了解。如果有人建议,破解在C ++中实现的方式将会非常有用。
class PetersonsFilterLock {
private:
volatile size_t no_of_threads;
volatile size_t *level;
volatile size_t *victim;
public:
PetersonsFilterLock(size_t num_threads);
void lock(size_t tid);
void unlock(size_t tid);
};
PetersonsFilterLock::PetersonsFilterLock(size_t num_threads) {
no_of_threads = num_threads;
level = new size_t[no_of_threads];
victim = new size_t[no_of_threads];
for(size_t i=0; i<no_of_threads; i++){
level[i] = 0;
}
}
void PetersonsFilterLock::lock(size_t tid) {
for(size_t i=1; i<no_of_threads; i++){
level[tid] = i;
victim[i] = tid;
for(size_t k=0; k<no_of_threads; k++){
while( k!=tid && level[k] >=i && victim[i] == tid) {}
}
}
}
void PetersonsFilterLock::unlock(size_t tid) {
level[tid] = 0;
}
感谢