информационная безопасность
без паники и всерьез
 подробно о проектеRambler's Top100
Spanning Tree Protocol: недокументированное применениеПортрет посетителяАтака на Internet
BugTraq.Ru
Русский BugTraq
 Анализ криптографических сетевых... 
 Модель надежности двухузлового... 
 Специальные марковские модели надежности... 
 Три миллиона электронных замков... 
 Doom на газонокосилках 
 Умер Никлаус Вирт 
главная обзор RSN блог библиотека закон бред форум dnet о проекте
bugtraq.ru / форум / programming
Имя Пароль
ФОРУМ
если вы видите этот текст, отключите в настройках форума использование JavaScript
регистрация





Легенда:
  новое сообщение
  закрытая нитка
  новое сообщение
  в закрытой нитке
  старое сообщение
  • Напоминаю, что масса вопросов по функционированию форума снимается после прочтения его описания.
  • Новичкам также крайне полезно ознакомиться с данным документом.
т.е. нужна? 09.11.02 23:47  Число просмотров: 1144
Автор: dl <Dmitry Leonov>
<"чистая" ссылка>
> кстати, из описания InterlockedExchange:
> >>>
> The variable pointed to by the Target parameter must be
> aligned on a 32-bit boundary; otherwise, this function will
> fail on multiprocessor x86 systems and any non-x86 systems.
> >>>
> т.е. если они не выровнены, то использовать мьютексы или
> т.п.?
> интересно, а зачем нужна синхронизация при доступе к 4
> выровненным байтам?
> ведь на 32-бит системах за один раз и читаются эти 4 байта
> как могут возникнуть проблемы?

The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

Simple reads and writes to properly-aligned 32-bit variables are atomic. In other words, when one thread is updating a 32-bit variable, you will not end up with only one portion of the variable updated; all 32 bits are updated in an atomic fashion. However, access is not guaranteed to be synchronized. If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation.

Simple reads and writes to properly-aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.

The interlocked functions should be used to perform complex operations in an atomic manner. The InterlockedIncrement and InterlockedDecrement functions combine the operations of incrementing or decrementing the variable and checking the resulting value. This atomic operation is useful in a multitasking operating system, in which the system can interrupt one thread's execution to grant a slice of processor time to another thread. Without such synchronization, one thread could increment a variable but be interrupted by the system before it can check the resulting value of the variable. A second thread could then increment the same variable. When the first thread receives its next time slice, it will check the value of the variable, which has now been incremented not once but twice. The interlocked variable-access functions protect against this kind of error.

Т.е. в ситуации, когда в одном потоке просто написано a = ++b; этот ++ сработает без проблем, будучи атомарной операцией, но нет никаких гарантий, что а получит именно это значение.
<programming>
нужна синхронизация для 4 байт? 09.11.02 19:52  
Автор: ggg <ggg> Статус: Elderman
<"чистая" ссылка>
в самом общем случае, т.е. для системы с несколькими процессорами

нужно прочитать или записать 4 байта
причём обратиться к ним могут разные потоки

нужна ли для этого случая синхронизация, типа мьютексов и т.п.?


у меня предположение, что если эти 4 байта начинаются с 4-байтной границы, то не нужна
(т.е. два процессора не могут одновременно обратиться к этим 4 байтам)
если я прав, то ещё один вопрос: выравниваются ли экспортируемые функции в Win32 на 4 байта?
Ну а ради чего придуманы всякие InterlockedIncrement и т.п.? 09.11.02 22:46  
Автор: dl <Dmitry Leonov>
<"чистая" ссылка>
т.е. нужна? 09.11.02 23:26  
Автор: ggg <ggg> Статус: Elderman
<"чистая" ссылка>
кстати, из описания InterlockedExchange:
>>>
The variable pointed to by the Target parameter must be aligned on a 32-bit boundary; otherwise, this function will fail on multiprocessor x86 systems and any non-x86 systems.
>>>

т.е. если они не выровнены, то использовать мьютексы или т.п.?

интересно, а зачем нужна синхронизация при доступе к 4 выровненным байтам?
ведь на 32-бит системах за один раз и читаются эти 4 байта
как могут возникнуть проблемы?
т.е. нужна? 09.11.02 23:47  
Автор: dl <Dmitry Leonov>
<"чистая" ссылка>
> кстати, из описания InterlockedExchange:
> >>>
> The variable pointed to by the Target parameter must be
> aligned on a 32-bit boundary; otherwise, this function will
> fail on multiprocessor x86 systems and any non-x86 systems.
> >>>
> т.е. если они не выровнены, то использовать мьютексы или
> т.п.?
> интересно, а зачем нужна синхронизация при доступе к 4
> выровненным байтам?
> ведь на 32-бит системах за один раз и читаются эти 4 байта
> как могут возникнуть проблемы?

The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

Simple reads and writes to properly-aligned 32-bit variables are atomic. In other words, when one thread is updating a 32-bit variable, you will not end up with only one portion of the variable updated; all 32 bits are updated in an atomic fashion. However, access is not guaranteed to be synchronized. If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation.

Simple reads and writes to properly-aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.

The interlocked functions should be used to perform complex operations in an atomic manner. The InterlockedIncrement and InterlockedDecrement functions combine the operations of incrementing or decrementing the variable and checking the resulting value. This atomic operation is useful in a multitasking operating system, in which the system can interrupt one thread's execution to grant a slice of processor time to another thread. Without such synchronization, one thread could increment a variable but be interrupted by the system before it can check the resulting value of the variable. A second thread could then increment the same variable. When the first thread receives its next time slice, it will check the value of the variable, which has now been incremented not once but twice. The interlocked variable-access functions protect against this kind of error.

Т.е. в ситуации, когда в одном потоке просто написано a = ++b; этот ++ сработает без проблем, будучи атомарной операцией, но нет никаких гарантий, что а получит именно это значение.
1




Rambler's Top100
Рейтинг@Mail.ru


  Copyright © 2001-2024 Dmitry Leonov   Page build time: 0 s   Design: Vadim Derkach