如何以“线程安全”的方式编写一个返回例如数字0-7循环的函数,确保每个调用都有一个新数字(如果> 7,则回绕)?
它应该是一个全局函数,所以如果“连接1”调用它并得到数字3,“连接2”应该在它调用时得到数字4,等等。
答案 0 :(得分:5)
根据docs,你可以循环序列:
t=# create sequence rr07 minvalue 0 maxvalue 7 cycle;
CREATE SEQUENCE
t=# select nextval('rr07');
nextval
---------
0
(1 row)
t=# select nextval('rr07');
nextval
---------
1
(1 row)
t=# select nextval('rr07');
nextval
---------
2
(1 row)
t=# select nextval('rr07');
nextval
---------
3
(1 row)
t=# select nextval('rr07');
nextval
---------
4
(1 row)
t=# select nextval('rr07');
nextval
---------
5
(1 row)
t=# select nextval('rr07');
nextval
---------
6
(1 row)
t=# select nextval('rr07');
nextval
---------
7
(1 row)
t=# select nextval('rr07');
nextval
---------
0
(1 row)