Multithreading issue

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
lgyer
Posts: 29
Joined: Fri Feb 26, 2021 8:09 am

Multithreading issue

Post by lgyer » Fri Mar 05, 2021 3:25 am

Hi,

I use _thread module to create two threads in main.py, and they are running with a "while" loop. When I want to use ctrl+C to stop these threads, they can't stop. How can I stop these thread?
The code as following.

Code: Select all

class Thread:
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None):
        self.target = target
        self.args = args
        self.kwargs = {} if kwargs is None else kwargs

    def start(self):
        _thread.start_new_thread(self.run, ())

    def run(self):
        self.target(*self.args, **self.kwargs)
  
def task1():
    print("run task1")
    while True:
      time.sleep(1)
      print("task1 running")

import time
import _thread
def task2():
    while True:
      print("Task2 running")
      time.sleep(1)

Thd1 = Thread(target=task1)
Thd2 = Thread(target=task2)
Thd1.start()
Thd2.start()

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Multithreading issue

Post by jimmo » Thu Mar 11, 2021 5:31 am

lgyer wrote:
Fri Mar 05, 2021 3:25 am
When I want to use ctrl+C to stop these threads, they can't stop.
I think the problem here is that your main program finishes and returns you back to the REPL. When you hit ctrl-C, the main thread (at the REPL) will handle it instead and have nothing to do.

If you hit Ctrl-D to soft reset, does that stop the threads?

lgyer
Posts: 29
Joined: Fri Feb 26, 2021 8:09 am

Re: Multithreading issue

Post by lgyer » Fri Mar 12, 2021 6:30 am

jimmo wrote:
Thu Mar 11, 2021 5:31 am
lgyer wrote:
Fri Mar 05, 2021 3:25 am
When I want to use ctrl+C to stop these threads, they can't stop.
I think the problem here is that your main program finishes and returns you back to the REPL. When you hit ctrl-C, the main thread (at the REPL) will handle it instead and have nothing to do.

If you hit Ctrl-D to soft reset, does that stop the threads?
Hi jimmo,
Thanks for your reply.
When I hit Ctrl-D to soft reset, the threads can be stopped. Is there any way to interrupt the sub-thread?

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Multithreading issue

Post by jimmo » Tue Jul 06, 2021 3:55 am

lgyer wrote:
Fri Mar 12, 2021 6:30 am
When I hit Ctrl-D to soft reset, the threads can be stopped. Is there any way to interrupt the sub-thread?
You'll need to set a global flags and have the threads check that flag (and terminate if it's set).

Post Reply