I want to run the function example() n number of times at same time without any delay concurrently, this current script is able to run n number of times but there is almost milliseconds of difference between each call. I want the function to be hit at same time. Is there any better way to do it ? I used multiprocess too in past, but it was slowing down my computer if I run more than n=100. Please suggest a good way
import threading,argparse,sys,subprocess
from time import strftime
def example(a):
time= strftime("%H:%M:%S")
print("Hello" +a)
print(time) # It should be same for all n concurrent, since we want all to hit same time
def main(argv):
parser = argparse.ArgumentParser(description="Hello")
parser.add_argument("-n", type=str, dest="n")
parser.add_argument("-a", type=str, dest="a")
global verbose
global simulated
verbose = args.verbose
n = args.n
a = args.a
for counter in range(1, int(n) + 1):
try:
t = threading.Thread(name="thread" + str(counter), target=example, args=(a))
t.start()
except Exception as e:
print(e)
if __name__ == '__main__':
try:
ret = main(sys.argv[1:])
sys.exit(ret)
except Exception as ex:
print('Error' + str(ex))
sys.exit(1)
You want to start a function in several threads at the same time. I never made it but an idea (not tested) would be - you start all 100 threads (and option you identify what is the usual time for starting all 100 threads 0.5s?) - in your threads you make waiting for a signal: a "GO" anywhere or a time/date stored anywhere in a file which will be probably "time start of first thread + 0.5s". When the time is met in the thread, then you execute the function. For the reason I dont know the inner life of threading, I cannot say to you if it will be for sure exactly the same time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.