美文网首页
模仿java中的雪花算法

模仿java中的雪花算法

作者: 李木的 | 来源:发表于2019-07-22 17:08 被阅读0次

    做商品生成订单的时候经常需要唯一标识,模仿一下雪花算法的oc版本。
    首先声明.h文件中引入c语言文件

    #ifndef TDSnowflake_h
    #define TDSnowflake_h
    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <sched.h>
    #include <unistd.h>
    #include <sys/syscall.h>
    #include <errno.h>
    #include <time.h>
    #include <stdint.h>
    #include <sys/time.h>
    #endif /* TDSnowflake_h */
    struct globle {
    int global_int:12;
    uint64_t last_stamp;
    int workid;
    int seqid;
    };
    void set_workid(int workid);
    pid_t gettid( void );
    uint64_t get_curr_ms(void);
    uint64_t wait_next_ms(uint64_t lastStamp);
    int atomic_incr(int id);
    uint64_t get_unique_id(void);
    

    .m文件中实现声明的生成19位随机值的方法

      #include "TDSnowflake.h"
      struct globle g_info;
      void set_workid(int workid)
      {
          g_info.workid = workid;
      }
      pid_t gettid( void )
      {
         return syscall( SYS_gettid );
      }
      uint64_t get_curr_ms()
      {
          struct timeval time_now;
          gettimeofday(&time_now,NULL);
          uint64_t ms_time=time_now.tv_sec*1000+time_now.tv_usec/1000;
          return ms_time;
      }
    
      uint64_t wait_next_ms(uint64_t lastStamp)
      {
          uint64_t cur = 0;
          do {
          cur = get_curr_ms();
          } while (cur <= lastStamp);
          return cur;
      }
      int atomic_incr(int id)
      {
           __sync_add_and_fetch( &id, 1 );
           return id;
      }
      uint64_t get_unique_id()
      {
           uint64_t uniqueId=0;
           uint64_t nowtime = get_curr_ms();
           uniqueId = nowtime<<22;
           uniqueId |=(g_info.workid&0x3ff)<<12;
           if (nowtime <g_info.last_stamp)
           {
             perror("error");
             exit(-1);
            }
           if(nowtime==g_info.last_stamp){
               g_info.seqid = atomic_incr(g_info.seqid)&(-1L ^ (-1L << 12L));
               if(g_info.seqid==0){
                   nowtime = wait_next_ms(g_info.last_stamp);
                 }
                }else{g_info.seqid = 0;}
               g_info.last_stamp = nowtime;
               uniqueId |=g_info.seqid;
              return uniqueId;
         }
    

    相关文章

      网友评论

          本文标题:模仿java中的雪花算法

          本文链接:https://www.haomeiwen.com/subject/lcwwlctx.html