开发者

Design problem: Running sequence numbr across multi-threaded processes

开发者 https://www.devze.com 2023-04-09 20:38 出处:网络
I have 3 multithreaded processes. I want to implement a sequence number generator (every call to it shall return next number in sequence).

I have 3 multithreaded processes. I want to implement a sequence number generator (every call to it shall return next number in sequence). All the three processes or their threads can request generation of next sequence number. I am looking for a very low latency solution.

Thanks in advance for开发者_如何转开发 ideas.

Sorry for missing this earlier. My platform is:- - Linux platform - C++


Since you don't provide much details just a general idea:

You write that there are 3 processes which run multiple threads... I assume they run on the same machine... another assumption: you are using some current version of Windows...

Implement shared memory (via MemoryMappedFile or its native counterpart) and use an atomic increment (InterlockedAdd64 or its managed counterpart Interlocked.Add) from each process to get the next number...

EDIT - after the addition of platform (Linux) by the OP:

You can use the same approach as described above with Linux too:

  • shared memory can be done via mmap API with the flag MAP_SHARED
  • atomic operations (like increment/decrement) can be done via libatomic see http://packages.debian.org/source/sid/libatomic-ops


Shared memory area stores the last number in the sequence. Every process, when it needs a new number in the sequence, calculates it and InterlockedCompareExchange()'s it with the old number. If the ICE() succeeds, it uses the number, if it doesn't, the routine is repeated until the ICE() succeeds.


if you are looking for one in JVM world:

class Sequencer {
  private AtomicLong sequenceNumber = new AtomicLong(0);
  public long next() { return sequenceNumber.getAndIncrement(); }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号