所以我想我理解信號和等待的源代碼(等待成爲鎖),但我不知道如何實現嘗試鎖。 這裏是我的等待代碼:嘗試鎖的源代碼是什麼?
//if s->type is zero it is a binary semaphore type
if (s->type == 0)
{
// binary semaphore
// if state is zero, then block task
if (s->state == 0)
{
// block task
// ?? move task from ready queue to blocked queue
//reschedule the tasks
return 1;
}
// state is non-zero (semaphore already signaled)
s->state = 0; // reset state, and don't block
return 0;
}
else
{
// counting semaphore
s->state--;
// ?? implement counting semaphore
if (s->state < 0)
{
}
}
這是我迄今一試鎖:
if (s->type == 0)
{
// binary semaphore
// if state is zero, then block task
if (s->state == 0)
{
tcb[curTask].event = s; // block task
tcb[curTask].state = S_BLOCKED;
removeNode(tcb[curTask].priority, READY_QUEUE, curTask);
enqueue(tcb[curTask].priority, curTask, BLOCKED_QUEUE);
return 1;
}
// state is non-zero (semaphore already signaled)
s->state = 1; // reset state, and don't block
return 0;
}
else
{
s->state--;
if (s->state >= 0)
{
s->state++;
}
else
{
tcb[curTask].event = s;
tcb[curTask].state = S_BLOCKED;
removeNode(tcb[curTask].priority, READY_QUEUE, curTask);
enqueue(tcb[curTask].priority, curTask, BLOCKED_QUEUE);
}
}
嘗試鎖定信號量,如果它已被其他進程鎖定,則立即返回(非阻塞)並返回一些錯誤代碼。 – SparKot