Вопрос по multithreading, c++ – разница между замком, барьером памяти, семафором

4

Эта статья:http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf (стр. 12) кажется, что разница между замком и барьером памяти

Я хотел бы знать, в чем разница между блокировкой, барьером памяти и семафором?

(While other questions might mention the difference between a lock and a synchronisation object, I found none about the difference between a lock and a memory barrier)

Ваш Ответ

3   ответа
8

  • A memory barrier is a method to order memory access. Compilers and CPU's can change this order to optimize, but in multithreaded environments, this can be an issue. The main difference with the others is that threads are not stopped by this.
  • A lock or mutex makes sure that code can only be accessed by 1 thread. Within this section, you can view the environment as singlethreaded, so memory barriers should not be needed.
  • a semaphore is basically a counter that can be increased (v()) or decreased (p()). If the counter is 0, then p() halts the thread until the counter is no longer 0. This is a way to synchronize threads, but I would prefer using mutexes or condition variables (controversial, but that's my opinion). When the initial counter is 1, then the semaphore is called a binary semaphore and it is similar to a lock.

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded xcrypt
Error: User Rate Limit Exceeded
2

Error: User Rate Limit Exceeded

Lock

Error: User Rate Limit Exceeded

lock (myObject)
{
    // Stuff to do when I acquire the lock
}

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Memory Barrier

Error: User Rate Limit Exceeded

Thread.MemoryBarrier();
public static Singleton Instance()
{
    if (_singletonInstance == null)
    {
        lock(myObject)
        {
            if (_singletonInstance == null)
            {
                _singletonInstance = new Singleton();
            }
        }
    }
}

Error: User Rate Limit Exceeded

Semaphores

Error: User Rate Limit Exceeded

8

Error: User Rate Limit Exceededmembar #StoreStoreError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded xcrypt
Error: User Rate Limit ExceededvolatileError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded xcrypt
stackoverflow.com/questions/10536309/…Error: User Rate Limit Exceededm_NumRunningThreads==0Error: User Rate Limit Exceeded xcrypt
Error: User Rate Limit ExceededvolatileError: User Rate Limit ExceededvolatileError: User Rate Limit Exceeded

Похожие вопросы