设计问题:跨多线程进程运行序列号
我有 3 个多线程进程。 我想实现一个序列号生成器(每次调用它都应按顺序返回下一个数字)。 所有三个进程或其线程都可以请求生成下一个序列号。 我正在寻找一个非常低延迟的解决方案。
预先感谢您的想法。
抱歉之前错过了这个。我的平台是:- - Linux平台 - C++
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++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您没有提供太多细节,只是提供一个一般想法:
您写道有 3 个运行多个线程的进程...我假设它们在同一台计算机上运行...另一个假设:您正在使用某些当前版本的 Windows。 ..
实现共享内存(通过
MemoryMappedFile
或其本机对应)并使用原子增量 (
InterlockedAdd64
或其托管对应项Interlocked.Add
) 从每个进程获取下一个数字...编辑 - 在OP添加平台(Linux)之后:
您可以使用相同的Linux 上也采用上述方法:
mmap
API 来完成,libatomic 来完成
参见 http://packages.debian.org/source/sid/libatomic-操作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 counterpartInterlocked.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:
mmap
API with the flagMAP_SHARED
libatomic
see http://packages.debian.org/source/sid/libatomic-ops共享内存区域存储序列中的最后一个数字。每个进程在需要序列中的新数字时都会对其进行计算,然后使用 InterlockedCompareExchange() 将其与旧数字进行比较。如果 ICE() 成功,则使用该数字,如果不成功,则重复该例程,直到 ICE() 成功。
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.
如果您正在 JVM 世界中寻找一个:
if you are looking for one in JVM world: