How can I invoke a thread multiple times in Python? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Call thread several times in pythonHow to stop and start a thread at willHow do I copy a file in Python?How can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How to return multiple values from a function?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to use threading in Python?

The Nth Gryphon Number

Co-worker has annoying ringtone

Why weren't discrete x86 CPUs ever used in game hardware?

How many time has Arya actually used Needle?

An adverb for when you're not exaggerating

Misunderstanding of Sylow theory

What makes a man succeed?

Google .dev domain strangely redirects to https

How do I find out the mythology and history of my Fortress?

How do living politicians protect their readily obtainable signatures from misuse?

Did Mueller's report provide an evidentiary basis for the claim of Russian govt election interference via social media?

How to save space when writing equations with cases?

Is there any word for a place full of confusion?

Is there hard evidence that the grant peer review system performs significantly better than random?

Is it possible for SQL statements to execute concurrently within a single session in SQL Server?

How does Belgium enforce obligatory attendance in elections?

How to compare two different files line by line in unix?

What are the discoveries that have been possible with the rejection of positivism?

If the probability of a dog barking one or more times in a given hour is 84%, then what is the probability of a dog barking in 30 minutes?

What is an "asse" in Elizabethan English?

Trademark violation for app?

What is the chair depicted in Cesare Maccari's 1889 painting "Cicerone denuncia Catilina"?

Crossing US/Canada Border for less than 24 hours

Significance of Cersei's obsession with elephants?



How can I invoke a thread multiple times in Python?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Call thread several times in pythonHow to stop and start a thread at willHow do I copy a file in Python?How can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How to return multiple values from a function?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to use threading in Python?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








6















I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:



class workers1(Thread): 
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers3(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

WorkerList1=[workers1(i) for i in range(X)]
WorkerList2=[workers2(i) for i in range(XX)]
WorkerList2=[workers3(i) for i in range(XXX)]


while True:
for thread in WorkerList1:
thread.run (start? join? or?)
for thread in WorkerList2:
thread.run (start? join? or?)
for thread in WorkerList3:
thread.run (start? join? or?)
do sth .


I am trying to have all the threads in all the WorkerList to start functioning at the same time, or at least start around the same time. After sometime once they were all terminated, I would like to invoke all the threads again.



If there were no loop, I can just use .start; but since I can only start a thread once, start apparently does not fit here. If I use run, it seems that all the threads start sequentially, not only the threads in the same list, but also threads from different lists.



Can anyone please help?










share|improve this question
























  • When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

    – Enak
    Mar 22 at 11:18

















6















I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:



class workers1(Thread): 
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers3(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

WorkerList1=[workers1(i) for i in range(X)]
WorkerList2=[workers2(i) for i in range(XX)]
WorkerList2=[workers3(i) for i in range(XXX)]


while True:
for thread in WorkerList1:
thread.run (start? join? or?)
for thread in WorkerList2:
thread.run (start? join? or?)
for thread in WorkerList3:
thread.run (start? join? or?)
do sth .


I am trying to have all the threads in all the WorkerList to start functioning at the same time, or at least start around the same time. After sometime once they were all terminated, I would like to invoke all the threads again.



If there were no loop, I can just use .start; but since I can only start a thread once, start apparently does not fit here. If I use run, it seems that all the threads start sequentially, not only the threads in the same list, but also threads from different lists.



Can anyone please help?










share|improve this question
























  • When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

    – Enak
    Mar 22 at 11:18













6












6








6


1






I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:



class workers1(Thread): 
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers3(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

WorkerList1=[workers1(i) for i in range(X)]
WorkerList2=[workers2(i) for i in range(XX)]
WorkerList2=[workers3(i) for i in range(XXX)]


while True:
for thread in WorkerList1:
thread.run (start? join? or?)
for thread in WorkerList2:
thread.run (start? join? or?)
for thread in WorkerList3:
thread.run (start? join? or?)
do sth .


I am trying to have all the threads in all the WorkerList to start functioning at the same time, or at least start around the same time. After sometime once they were all terminated, I would like to invoke all the threads again.



If there were no loop, I can just use .start; but since I can only start a thread once, start apparently does not fit here. If I use run, it seems that all the threads start sequentially, not only the threads in the same list, but also threads from different lists.



Can anyone please help?










share|improve this question
















I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:



class workers1(Thread): 
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

class workers3(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
do some stuff

WorkerList1=[workers1(i) for i in range(X)]
WorkerList2=[workers2(i) for i in range(XX)]
WorkerList2=[workers3(i) for i in range(XXX)]


while True:
for thread in WorkerList1:
thread.run (start? join? or?)
for thread in WorkerList2:
thread.run (start? join? or?)
for thread in WorkerList3:
thread.run (start? join? or?)
do sth .


I am trying to have all the threads in all the WorkerList to start functioning at the same time, or at least start around the same time. After sometime once they were all terminated, I would like to invoke all the threads again.



If there were no loop, I can just use .start; but since I can only start a thread once, start apparently does not fit here. If I use run, it seems that all the threads start sequentially, not only the threads in the same list, but also threads from different lists.



Can anyone please help?







python multithreading






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 9 '12 at 13:40









Sergey K.

20.9k1385162




20.9k1385162










asked Nov 8 '10 at 8:13









user500432user500432

31113




31113












  • When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

    – Enak
    Mar 22 at 11:18

















  • When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

    – Enak
    Mar 22 at 11:18
















When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

– Enak
Mar 22 at 11:18





When defining the Arrays shouldn't the second WorkerList2 be a WorkerList3 instead?

– Enak
Mar 22 at 11:18












3 Answers
3






active

oldest

votes


















11














there are a lot of misconceptions here:



  • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)


  • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.


  • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.


additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.






share|improve this answer

























  • but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

    – user500432
    Nov 8 '10 at 8:54












  • right, i edited my answer...

    – Adrien Plisson
    Nov 8 '10 at 9:13


















2














If you would call thread.start() in the loops, you would actually start every thread only once, because all the entries in your list are distinct thread objects (it does not matter they belong to the same class). You should never call the run() method of a thread directly -- it is meant to be called by the start() method. Calling it directly would not call it in a separate thread.






share|improve this answer























  • If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

    – user500432
    Nov 8 '10 at 8:57











  • The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

    – Sven Marnach
    Nov 8 '10 at 9:04



















1














I had this same dilemma and came up with this solution which has worked perfectly for me. It also allows a thread-killing decorator to be used efficiently.



The key feature is the use of a thread refresher which is instantiated and .started in main. This thread-refreshing thread will run a function that instantiates and starts all other (real, task-performing) threads. Decorating the thread-refreshing function with a thread-killer allows you to kill all threads when a certain condition is met, such as main terminating.



@ThreadKiller(arg) #qu'est-ce que c'est
def RefreshThreads():
threadTask1 = threading.Thread(name = "Task1", target = Task1, args = (anyArguments))
threadTask2 = threading.Thread(name = "Task2", target = Task2, args = (anyArguments))
threadTask1.start()
threadTask2.start()

#Main
while True:
#do stuff
threadRefreshThreads = threading.Thread(name = "RefreshThreads", target = RefreshThreads, args = ())
threadRefreshThreads.start()





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4122188%2fhow-can-i-invoke-a-thread-multiple-times-in-python%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    11














    there are a lot of misconceptions here:



    • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)


    • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.


    • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.


    additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.






    share|improve this answer

























    • but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

      – user500432
      Nov 8 '10 at 8:54












    • right, i edited my answer...

      – Adrien Plisson
      Nov 8 '10 at 9:13















    11














    there are a lot of misconceptions here:



    • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)


    • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.


    • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.


    additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.






    share|improve this answer

























    • but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

      – user500432
      Nov 8 '10 at 8:54












    • right, i edited my answer...

      – Adrien Plisson
      Nov 8 '10 at 9:13













    11












    11








    11







    there are a lot of misconceptions here:



    • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)


    • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.


    • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.


    additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.






    share|improve this answer















    there are a lot of misconceptions here:



    • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)


    • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.


    • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.


    additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 22 at 11:01

























    answered Nov 8 '10 at 8:21









    Adrien PlissonAdrien Plisson

    16.5k43669




    16.5k43669












    • but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

      – user500432
      Nov 8 '10 at 8:54












    • right, i edited my answer...

      – Adrien Plisson
      Nov 8 '10 at 9:13

















    • but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

      – user500432
      Nov 8 '10 at 8:54












    • right, i edited my answer...

      – Adrien Plisson
      Nov 8 '10 at 9:13
















    but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

    – user500432
    Nov 8 '10 at 8:54






    but it I am using the start() method in the loop, my program may actually give me a runtime error, saying that the thread is already started. So I am not able to invoke the run method within each thread again.

    – user500432
    Nov 8 '10 at 8:54














    right, i edited my answer...

    – Adrien Plisson
    Nov 8 '10 at 9:13





    right, i edited my answer...

    – Adrien Plisson
    Nov 8 '10 at 9:13













    2














    If you would call thread.start() in the loops, you would actually start every thread only once, because all the entries in your list are distinct thread objects (it does not matter they belong to the same class). You should never call the run() method of a thread directly -- it is meant to be called by the start() method. Calling it directly would not call it in a separate thread.






    share|improve this answer























    • If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

      – user500432
      Nov 8 '10 at 8:57











    • The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

      – Sven Marnach
      Nov 8 '10 at 9:04
















    2














    If you would call thread.start() in the loops, you would actually start every thread only once, because all the entries in your list are distinct thread objects (it does not matter they belong to the same class). You should never call the run() method of a thread directly -- it is meant to be called by the start() method. Calling it directly would not call it in a separate thread.






    share|improve this answer























    • If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

      – user500432
      Nov 8 '10 at 8:57











    • The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

      – Sven Marnach
      Nov 8 '10 at 9:04














    2












    2








    2







    If you would call thread.start() in the loops, you would actually start every thread only once, because all the entries in your list are distinct thread objects (it does not matter they belong to the same class). You should never call the run() method of a thread directly -- it is meant to be called by the start() method. Calling it directly would not call it in a separate thread.






    share|improve this answer













    If you would call thread.start() in the loops, you would actually start every thread only once, because all the entries in your list are distinct thread objects (it does not matter they belong to the same class). You should never call the run() method of a thread directly -- it is meant to be called by the start() method. Calling it directly would not call it in a separate thread.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 8 '10 at 8:24









    Sven MarnachSven Marnach

    362k80759703




    362k80759703












    • If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

      – user500432
      Nov 8 '10 at 8:57











    • The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

      – Sven Marnach
      Nov 8 '10 at 9:04


















    • If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

      – user500432
      Nov 8 '10 at 8:57











    • The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

      – Sven Marnach
      Nov 8 '10 at 9:04

















    If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

    – user500432
    Nov 8 '10 at 8:57





    If my thread is already started, and finished execution, how can I invoke the run method embedded within the thread again? My point was to call the run method within each thread multiple times

    – user500432
    Nov 8 '10 at 8:57













    The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

    – Sven Marnach
    Nov 8 '10 at 9:04






    The run() method of every thread is only invoked once. Write a loop inside run(), or use some producer-consumer pattern using the queue module.

    – Sven Marnach
    Nov 8 '10 at 9:04












    1














    I had this same dilemma and came up with this solution which has worked perfectly for me. It also allows a thread-killing decorator to be used efficiently.



    The key feature is the use of a thread refresher which is instantiated and .started in main. This thread-refreshing thread will run a function that instantiates and starts all other (real, task-performing) threads. Decorating the thread-refreshing function with a thread-killer allows you to kill all threads when a certain condition is met, such as main terminating.



    @ThreadKiller(arg) #qu'est-ce que c'est
    def RefreshThreads():
    threadTask1 = threading.Thread(name = "Task1", target = Task1, args = (anyArguments))
    threadTask2 = threading.Thread(name = "Task2", target = Task2, args = (anyArguments))
    threadTask1.start()
    threadTask2.start()

    #Main
    while True:
    #do stuff
    threadRefreshThreads = threading.Thread(name = "RefreshThreads", target = RefreshThreads, args = ())
    threadRefreshThreads.start()





    share|improve this answer





























      1














      I had this same dilemma and came up with this solution which has worked perfectly for me. It also allows a thread-killing decorator to be used efficiently.



      The key feature is the use of a thread refresher which is instantiated and .started in main. This thread-refreshing thread will run a function that instantiates and starts all other (real, task-performing) threads. Decorating the thread-refreshing function with a thread-killer allows you to kill all threads when a certain condition is met, such as main terminating.



      @ThreadKiller(arg) #qu'est-ce que c'est
      def RefreshThreads():
      threadTask1 = threading.Thread(name = "Task1", target = Task1, args = (anyArguments))
      threadTask2 = threading.Thread(name = "Task2", target = Task2, args = (anyArguments))
      threadTask1.start()
      threadTask2.start()

      #Main
      while True:
      #do stuff
      threadRefreshThreads = threading.Thread(name = "RefreshThreads", target = RefreshThreads, args = ())
      threadRefreshThreads.start()





      share|improve this answer



























        1












        1








        1







        I had this same dilemma and came up with this solution which has worked perfectly for me. It also allows a thread-killing decorator to be used efficiently.



        The key feature is the use of a thread refresher which is instantiated and .started in main. This thread-refreshing thread will run a function that instantiates and starts all other (real, task-performing) threads. Decorating the thread-refreshing function with a thread-killer allows you to kill all threads when a certain condition is met, such as main terminating.



        @ThreadKiller(arg) #qu'est-ce que c'est
        def RefreshThreads():
        threadTask1 = threading.Thread(name = "Task1", target = Task1, args = (anyArguments))
        threadTask2 = threading.Thread(name = "Task2", target = Task2, args = (anyArguments))
        threadTask1.start()
        threadTask2.start()

        #Main
        while True:
        #do stuff
        threadRefreshThreads = threading.Thread(name = "RefreshThreads", target = RefreshThreads, args = ())
        threadRefreshThreads.start()





        share|improve this answer















        I had this same dilemma and came up with this solution which has worked perfectly for me. It also allows a thread-killing decorator to be used efficiently.



        The key feature is the use of a thread refresher which is instantiated and .started in main. This thread-refreshing thread will run a function that instantiates and starts all other (real, task-performing) threads. Decorating the thread-refreshing function with a thread-killer allows you to kill all threads when a certain condition is met, such as main terminating.



        @ThreadKiller(arg) #qu'est-ce que c'est
        def RefreshThreads():
        threadTask1 = threading.Thread(name = "Task1", target = Task1, args = (anyArguments))
        threadTask2 = threading.Thread(name = "Task2", target = Task2, args = (anyArguments))
        threadTask1.start()
        threadTask2.start()

        #Main
        while True:
        #do stuff
        threadRefreshThreads = threading.Thread(name = "RefreshThreads", target = RefreshThreads, args = ())
        threadRefreshThreads.start()






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 19 '18 at 16:25

























        answered Apr 19 '18 at 14:45









        Ctrl SCtrl S

        645824




        645824



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4122188%2fhow-can-i-invoke-a-thread-multiple-times-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript