4. (10 points) Your machine provides atomic exchange (xchg) instruction as its m
ID: 3708597 • Letter: 4
Question
4. (10 points) Your machine provides atomic exchange (xchg) instruction as its multiprocessor atomic primitive. The semantic and definition of the xchg instruction is shown below /* atomic exchange instruction. rl, r2 are registers. atomically swap value in register r2 with memory referenced by rl */ xchg r2, [r1]; swap [r1] with r2 A C 'wrapper function 'exchange()', provided by runtime library, allows programmer to use this primitive int exchange(int value, int *ptr) asm( xchg value, [ptr); return value; Your task is to implement a spinlock using this exchange() primitive class SpinLock private: int value 0; /1 e FREE; 1 BUSY public: void acquire) // implement this using exchange() void release) // implement this 1;Explanation / Answer
/* for simplicity, exchange function is dummy here, and assumed to be atomic, its working code without any errors*/
#include <iostream>
using namespace std;
int exchange(int value, int * ptr){
*ptr = value;
//asm(" xchg value, [ptr] ");
}
void block(){
std::cout << "block";
}
class SpinLock {
private:
int value = 0;// 0 = free 1= busy
public:
void acquire(){
while (value == 1) {
block();
}
//int *vpt = &value;
exchange(1, &value);
cout << "acquired" << endl;
}
void release(){
//int *vpt = &value;
exchange(0, &value);
cout << "released" << endl;
}
};
int main(){
SpinLock s = SpinLock();
s.acquire();
s.acquire();
s.release();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.