is this okay?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • siliconmike

    #1

    is this okay?

    pseudocode:

    function generate_unique _id()
    {
    mkdir("lock");

    if successful
    {
    $id = 10 digit random number;
    make sure that $id does not exist in our table
    if it does, generate a new one

    insert $id into our table;

    rmdir("lock");
    }
    else try mkdir again
    }

    do you see any race conditions?

    this idea could be dangerous if the script died before rmdir("lock")..
    any solution?

    [I can't use auto-increment .. long story]

    Mike

  • Iván Sánchez Ortega

    #2
    Re: is this okay?

    -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1

    siliconmike wrote:
    [color=blue]
    > mkdir("lock");[/color]

    Why don't you use the flock() mechanism instead??


    - --
    - ----------------------------------
    Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

    Un hombre con pereza es un reloj sin cuerda.- Balmes.
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.2 (GNU/Linux)

    iD8DBQFDWhrc3jc Q2mg3Pc8RAubuAJ 9UpWw+7wqBftaSQ +Q+QXZ07tC7ZgCf RXI0
    hQFGVcJJc7zopnu pH4160dc=
    =gGrZ
    -----END PGP SIGNATURE-----

    Comment

    • Andy Hassall

      #3
      Re: is this okay?

      On 21 Oct 2005 17:58:41 -0700, "siliconmik e" <siliconmike@ya hoo.com> wrote:
      [color=blue]
      >pseudocode:
      >
      >function generate_unique _id()
      >{
      > $id = 10 digit random number;
      > make sure that $id does not exist in our table
      > if it does, generate a new one
      >
      > insert $id into our table;[/color]

      You mention a "table", so I assume this is going into a database.

      If so, simply add a unique constraint to the column, and leave the locking to
      the database.

      Don't check if it exists with a SELECT since that introduces a race condition;
      attempt the INSERT, and catch the unique key violation if there is one.
      --
      Andy Hassall :: andy@andyh.co.u k :: http://www.andyh.co.uk
      http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool

      Comment

      Working...