模仿java中的雪花算法

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

#ifndef TDSnowflake_h
#define TDSnowflake_h
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#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 

你可能感兴趣的:(模仿java中的雪花算法)