Created
September 24, 2013 07:46
-
-
Save codetalks-new/6681583 to your computer and use it in GitHub Desktop.
以多线程及theading.Rlock,或者gevent加线程生成不可得重复的id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__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