Критический Раздел всегда быстрее?

Вы можете использовать некоторые и RegExp

let filter =["ABDC","ADBAC"]

var string1 = "ABCD";
var string2 = "ABDC sample";
var string3 = "ADBACABDC";

let match = (input) =>filter.some(e=>{
    let regEx = new RegExp(e, 'g')
    return regEx.test(input)
})

console.log(match(string1))
console.log(match(string2))
console.log(match(string3))
[119 ]

23
задан aJ. 12 May 2009 в 15:26
поделиться

5 ответов

Когда они говорят, что критический раздел является «быстрым», они имеют в виду «дешево приобрести его, когда он еще не заблокирован другим потоком».

[Обратите внимание, что если он уже заблокирован другим потоком, то почти не имеет значения, насколько он быстр.]

Причина, по которой это быстро, заключается в том, что до перехода в ядро, оно использует эквивалент InterlockedIncrement в одном из этих полей LONG (возможно, в поле LockCount ), и если это удается, то он считает блокировку приобретен, не входя в ядро.

API InterlockedIncrement , я думаю, реализован в пользовательском режиме как код операции «LOCK INC» ... другими словами, вы можете получить неоспоримый критический раздел, не выполняя никаких действий. кольцевой переход в ядро ​​вообще.

37
ответ дан 29 November 2019 в 00:54
поделиться

In performance work, few things fall into the "always" category :) If you implement something yourself that is similar to an OS critical section using other primitives then odds are that will be slower in most cases.

The best way to answer your question is with performance measurements. How OS objects perform is very dependent on the scenario. For example, critical sections are general considered 'fast' if contention is low. They are also considered fast if the lock time is less than the spin count time.

The most important thing to determine is if contention on a critical section is the first order limiting factor in your application. If not, then simply use a critical section normaly and work on your applications primary bottleneck (or necks).

If critical section performance is critical, then you can consider the following.

  1. Carefully set the spin lock count for your 'hot' critical sections. If performance is paramount, then the work here is worth it. Remember, while the spin lock does avoid the user mode to kernel transition, it consumes CPU time at a furious rate - while spinning, nothing else gets to use that CPU time. If a lock is held for long enough, then the spinning thread will actual block, freeing up that CPU to do other work.
  2. If you have a reader/writer pattern then consider using the Slim Reader/Writer (SRW) locks. The downside here is they are only available on Vista and Windows Server 2008 and later products.
  3. You may be able to use condition variables with your critical section to minimize polling and contention, waking threads only when needed. Again, these are supported on Vista and Windows Server 2008 and later products.
  4. Consider using Interlocked Singly Linked Lists (SLIST)- these are efficient and 'lock free'. Even better, they are supported on XP and Windows Server 2003 and later products.
  5. Examine your code - you may be able to break up a 'hot' lock by refactoring some code and using an interlocked operation, or SLIST for synchronization and communication.

In summary - tuning scenarios that have lock contention can be challenging (but interesting!) work. Focus on measuring your applications performance and understanding where your hot paths are. The xperf tools in the Windows Performance Tool kit is your friend here :) We just released version 4.5 in the Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1 (ISO is here, web installer here). You can find the forum for the xperf tools here. V4.5 fully supports Win7, Vista, Windows Server 2008 - all versions.

26
ответ дан 29 November 2019 в 00:54
поделиться

CriticalSections быстрее, но InterlockedIncrement / InterlockedDecrement больше. См. Этот пример использования реализации Полная копия LightweightLock .

4
ответ дан 29 November 2019 в 00:54
поделиться

The CriticalSections will spin a short while (few ms) and keep checking if the lock is free. After the spin count 'times out', it will then fall back to the kernel event. So in the case where the holder of the lock gets out quickly, you never have to make the expensive transition to kernel code.

EDIT: Went and found some comments in my code: apparently the MS Heap Manager uses a spin count of 4000 (integer increments, not ms)

3
ответ дан 29 November 2019 в 00:54
поделиться

Вот способ взглянуть на это:

Если нет разногласий, то спин-блокировка выполняется очень быстро по сравнению с переходом в режим ядра для мьютекса.

Когда есть раздор, CriticalSection немного дороже, чем использование Mutex напрямую (из-за дополнительной работы по обнаружению состояния спин-блокировки).

Таким образом, он сводится к средневзвешенному, где веса зависят от специфики вашего шаблона вызова. При этом, если у вас мало разногласий, то CriticalSection - большая победа. Если, с другой стороны, у вас постоянно много разногласий, вы заплатите очень небольшой штраф за использование Mutex напрямую. Но в этом случае вы получите мало, переключившись на Mutex, поэтому вам, вероятно, лучше попытаться уменьшить конкуренцию.

тогда CriticalSection - большая победа. Если, с другой стороны, у вас постоянно много разногласий, вы заплатите очень небольшой штраф за использование Mutex напрямую. Но в этом случае вы получите мало, переключившись на Mutex, поэтому вам, вероятно, лучше попытаться уменьшить конкуренцию.

тогда CriticalSection - большая победа. Если, с другой стороны, у вас постоянно много разногласий, вы заплатите очень небольшой штраф за использование Mutex напрямую. Но в этом случае вы получите мало, переключившись на Mutex, поэтому вам, вероятно, лучше попытаться уменьшить конкуренцию.

1
ответ дан 29 November 2019 в 00:54
поделиться
Другие вопросы по тегам:

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