Skip to content

Instantly share code, notes, and snippets.

@gautamkrishnar
Created July 13, 2017 06:40
Show Gist options
  • Save gautamkrishnar/d7ad136fc2694a08404dc054a3733f1b to your computer and use it in GitHub Desktop.
Save gautamkrishnar/d7ad136fc2694a08404dc054a3733f1b to your computer and use it in GitHub Desktop.
A simple python thread based random number generator
import threading
x=0 #to get a random number
killswitch = False # To kill thread after use
def threaded_return(que):
"""
Returning data from thread safely (Returns current value of x)
:param que:
:return:
"""
global x
que.put(x)
def thread_fn():
"""
This is a threaded function (counts from 0 to 10000 for infinite times untill killswitch is True)
:return:
"""
global x
global killswitch
while True:
if killswitch:
break
if x==10000:
x=0
continue
x=x+1
def kill():
"""
To send kill signal to the thread
:return:
"""
global killswitch
killswitch = True
global th
th.join()
def run():
global th
th = threading.Thread(target=thread_fn)
th.start()
import queue
que = queue.Queue()
import lib
def main():
lib.run()
print("Main function...")
for i in range(20):
lib.threaded_return(que=que)
x = str(que.get())
print("Returned from queue: "+x)
lib.kill()
exit()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
lib.kill()
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment