i am studying synchronization , and i found this topic the hardest thing i came across in coding thus far ! i really need help , and maybe i will start to understand this subject ! i learned about mutex with simple lock and unlock , and i learned about condition varibales and ( that uses signal and wait) i also undesrtand the semaphores , but when i come acros a questions that gives me a new "synchronization" tool and askes me to implement another mutex tools with it i just don't know where to began .
for example let assume i have this new synchronization tool , and i was asked to implement a simple mutex using it , how to began solving such a thing ? this is the literally the question ! i am lost any tips ? (plz don't close the question i realy need some tips i am hopeless)
typedef struct newSem{
int value;
} newSem;
// Initialize the newSemto value 0.
void newSem(newSem* h) {
h->value = 0;
}
// Block until the newSem has value >= bound, then atomically increment its value by delta.
void H(newSem* h, int bound, int delta) {
// This is pseudocode; a real newSem implementation would block, not
// spin, and would ensure that the test and the increment happen in one
// atomic step.
while (h->value < bound) {
sched_yield();
}
h->value += delta;
}
for example to implement this usin the newSem :
typedef struct mutex {
newSem h;
} mutex;
void mutex_init(mutex* m) {
//TODO
}
void mutex_lock(mutex* m) {
//TODO
}
void mutex_unlock(mutex* m) {
//TODO
}
If you have a semaphore, then implementing a mutex is trivial since it is basically a sempahore of size 1.
Say you have your semaphore initialized to 0
as shown in the question. Then if you call H(h, 0, -1)
by two threads, the first one to arrive will go in right away and will set the value to -1
. The other thread will have to wait because -1 < 0
. Then the first thread calls H(h, -1, 1)
to exit and put the value back at 0
, so the second thread can now go in.