Python multithreading: spawning multiple threads, only last one executed -
i'm trying write basic simulator clients arriving @ random arrival times , stay random amount of time , leave again.
the idea every time client generated, seperate thread spawned client deleted after random amount of time (see delete_user() function).
def delete_user(user): time.sleep(random.randint(5,20)) print "user %s left @ %s" % (user.id, time.ctime()) def start_simulation(number_users, interval): in range(number_users): t = random.expovariate(1.0 / interval) time.sleep(t) # wait random time before generating new user user = generate_user() print "user %s generated @ %s" % (user.id, time.ctime()) worker = threading.thread(target=delete_user, args=(user,)) worker.start()
the problem delete_user() executed once, last user generated. seems though last spawned thread something.
this output:
user b490fbd0-8740-4d7e-a3a6-d46449ff918b generated @ wed apr 1 07:22:47 2015 user 844122d9-4032-4866-9e07-eb86f076a531 generated @ wed apr 1 07:22:49 2015 user 91e238fc-4ed1-4a81-a434-9a50d3b01fed generated @ wed apr 1 07:22:52 2015 user 877c8e3f-2b3d-4997-9644-98d078388427 generated @ wed apr 1 07:22:52 2015 user a77dcefc-8ea1-467d-8365-923b789ab4bb generated @ wed apr 1 07:22:54 2015 user a77dcefc-8ea1-467d-8365-923b789ab4bb left @ wed apr 1 07:23:02 2015
am overlooking something? or there easier way achieve same functionality need?
thanks
moved comment section:
a quick google has turned this: http://docs.python.org/2/library/sched.html, think pretty want.
Comments
Post a Comment