Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Any idea on how to build an application that provides unique keys each time it get called by another process.
Calling process isn't my problem here, my problem is how to sync between two(or more) processes and preventing it from providing the same key to both of them.

I'd really appreciate your help in this issue, please only outline the solution and I'll try to implement it.

share|improve this question

Just use a GUID as your key. It's universally unique.

share|improve this answer
Or just use getpid() if you're on UNIX/Linux – Charles Salvia Apr 13 '12 at 20:03
If you use GUID, make sure that you are using a thread-safe call in your programming language of choice. – NoChance Apr 14 '12 at 0:28

not to be to basic but why not just have an incrementing integer (ack a global) for your key. Have it initialize at start up. Save the calling process and key in a dictionary if you need the reference both ways. You could do this with a class, or store it in a database depending on your need.

share|improve this answer

I haven't used C in ages, but there must be some way to synchronize your code so only one processes, or thread, can get into it at one time. Something like:

int unique_index = 0;

synchronized int GetUnique()  {
    int i = unique_index++;
    return i;

You'd want to make sure unique_index was accessed only from within GetUnique or other synchronized code. If it gets called from 10,000 threads all at the same time, you might experience some delays and you'd need something more clever, but that should do for a start.

If this program is to start and stop and deliver unique numbers to other programs, you'd need to make sure GetUnique would not do anything until the program was up and had recovered its data (unique_index) from a file or where ever. Likewise, GetUnique would have to stop responding before data was saved during shutdown.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.