且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是互斥和信号灯实际上呢?

更新时间:2023-02-26 18:17:36

当一个线程试图获取一个互斥锁,如果互斥锁已经保持,则通常会使用一个调用操作系统内核,以表明它等待,然后在当前拥有锁的线程解锁互斥那么它将对操作系统内核调用唤醒等待线程。

这同样适用于一个信号量,但它只有块,如果计数递减零以下,并且当计数高于零增加回到线程仅唤醒

一个忙等待的就是在等待着什么,当你不阻止或睡眠,但在一个循环中重复轮询,因此处理器总是很忙,但没有做什么有用的东西。

要真正实现一个忙等待,你需要一个原子变量,但POSIX线程并没有提供这样的事情,所以你不能真正在写的pthreads忙等待。你可以得到最接近的是锁定一个互斥体,读一个标志,解锁互斥体,循环,如果没有设置该标志。这种反复锁定和解锁互斥体,但不等待数据做好准备。在这种情况下,你应该使用条件变量来代替。

通常情况下,你说一个线程处于休眠状态,如果它已经呼吁像 usleep 中止其自己的运行的时间在指定的时间。这是相对于阻塞,在那里它在等待将被另一线程提供的特定信号。

I want some clarification regarding mutex and semaphore.
My question is,

  1. What mutex actually do when a thread tries to enter a region locked by a mutex, a. it waits for the lock to be released? or b. it goes to sleep until the lock is released. In that case how it is wake up again when the lock is released?
  2. Same question as 1, but in this case it is semaphore.
  3. Can you give me some code regarding busy waiting in pthread in C, and also a case where thread goes to sleep instead of waiting? does sleep mean it is blocked or sleeping is another kind of busy waiting?
  4. i want to know some programs where this situations are covered, for example some c source codes where busy waiting, blocking etc are implemented.

When a thread tries to acquire a lock on a mutex, if that mutex is already held then typically it will use a call to the OS kernel to indicate that it is waiting, and then when the thread that currently holds the lock unlocks the mutex then it will make a call to the OS kernel to wake one of the waiting threads.

The same applies to a semaphore, except it only blocks if the count is decremented below zero, and threads are only woken when the count is increased back above zero.

A busy wait is where you don't block or sleep when waiting for something, but repeatedly poll in a loop, so the processor is always busy, but not doing anything useful.

To truly achieve a busy wait, you need an atomic variable, but POSIX threads does not provide such a thing, so you cannot truly write a busy wait in pthreads. The closest you can get is to lock a mutex, read a flag, unlock the mutex, loop if the flag was not set. This repeatedly locks and unlocks the mutex, but does not wait for the data to be ready. In this situation you should use a condition variable instead.

Typically, you say a thread is sleeping if it has called something like usleep to suspend its own execution for a specified period of time. This is as opposed to to blocking, where it is waiting for a specific signal which will be provided by another thread.