Skip to content

Instantly share code, notes, and snippets.

@codetalks-new
Created September 24, 2013 07:46
Show Gist options
  • Save codetalks-new/6681583 to your computer and use it in GitHub Desktop.
Save codetalks-new/6681583 to your computer and use it in GitHub Desktop.
以多线程及theading.Rlock,或者gevent加线程生成不可得重复的id
__author__ = 'Alec'
import threading
import time
import thread
import gevent
cids = []
_cid_rlock = threading.RLock()
def generate_cid():
with _cid_rlock:
return long((time.time()-1377964800.000000)*1000000000)
def generate_many_cid():
for i in range(60):
cids.append(generate_cid())
def main(): #Use thread.start_new_thread() to create 2 new threads
# thread.start_new_thread(generate_many_cid, ())
# thread.start_new_thread(generate_many_cid, ())
# thread.start_new_thread(generate_many_cid, ())
# thread.start_new_thread(generate_many_cid, ())
gevent.joinall([
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
gevent.spawn(generate_many_cid),
])
time.sleep(5)
print cids
s_length = len(cids)
print('S_Lenght: %s' % s_length)
after = len(set(cids))
print(' After_length: %s' % after)
assert s_length == after
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment