Python exit program with threads

How to Kill a Thread in Python

You can kill a thread by killing its parent process via the terminate() and kill() methods.

In this tutorial you will discover how to kill a thread in Python.

Need to Kill a Thread

A thread is a thread of execution in a computer program.

Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create additional threads in our program in order to execute code concurrently.

Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.

You can learn more about Python threads in the guide:

In concurrent programming, you sometimes need to forcefully terminate or kill a thread.

Killing a thread means that there is no facility to gracefully stop the thread.

This may be for many reasons, such as:

  • The task is out of control or is broken in some critical way.
  • The outcome of the task executed by the thread is no longer needed.
  • The dependencies of the task are no longer available.

How can we kill a thread in Python?

Run your loops using all CPUs, download my FREE book to learn how.

Alternatives to Killing a Thread

Forcefully terminating or killing a thread is a drastic action.

Before we look at how to kill a thread, let’s look at alternatives.

There are perhaps three common alternatives you may want to consider they are:

  1. Stop the thread.
  2. Raise an exception in the thread.
  3. Make the thread a daemon thread.

Let’s take a closer look at each in turn.

Stop a Thread

Python does not provide the ability in the threading API to stop a thread.

Instead, we can add this functionality to our code directly.

A thread can be stopped using a shared boolean variable such as a threading.Event.

A threading.Event is a thread-safe boolean variable flag that can be either set or not set. It can be shared between threads and checked and set without fear of a race condition.

A new event can be created and then shared between threads, for example:

The event is created in the ‘not set‘ or False state.

We may have a task in a custom function that is run in a new thread. The task may iterate, such as in a while-loop or a for-loop.

We can update our task function to check the status of an event each iteration.

If the event is set true, we can exit the task loop or return from the task() function, allowing the new thread to terminate.

The status of the threading.Event can be checked via the is_set() function.

Читайте также:  Тег IMG

The main thread, or another thread, can then set the event in order to stop the new thread from running.

The event can be set or made True via the set() function.

You can learn more about stopping a thread in this tutorial:

Raise Exception in Thread

Like stopping a thread, the Python threading API does not provide a mechanism to raise an exception in a target thread.

Instead, we can add this functionality to our code directly using a threading.Event.

As with stopping a thread, we can create an event and use it as a thread-safe shared boolean variable. A new event can be created and then shared between threads, for example:

Our target task function executing in a new thread can check the status of the event each iteration of the task.

If set, the task function can raise an exception. The exception will not be handled and instead we will let it bubble up to the top level of the thread, in which case the thread will terminate.

The main thread, or another thread, can then set the event in order to trigger an exception to stop the new thread.

The event can be set or made True via the set() function.

You can learn more about unexpected exceptions in threads in this tutorial:

Make Daemon Thread

A thread may be configured to be a daemon thread.

Daemon threads is the name given to background threads. By default, threads are non-daemon threads.

A Python program will only exit when all non-daemon threads have finished. For example, the main thread is a non-daemon thread. This means that daemon threads can run in the background and do not have to finish or be explicitly excited for the program to end.

We can determine if a thread is a daemon thread via the “daemon” attribute.

A thread can be configured to be a daemon by setting the “daemon” argument to True in the threading.Thread constructor.

We can also configure a thread to be a daemon thread after it has been constructed via the “daemon” property.

You can learn more about daemon threads in this tutorial:

Now that we know some alternatives, let’s look at how to kill a thread.

Confused by the threading module API?
Download my FREE PDF cheat sheet

How to Kill a Thread

A thread can be terminated or killed by forcibly terminating or killing its parent process.

Recall that each thread belongs to a process. A process is an instance of the Python interpreter, and a thread is a thread of execution that executes code within a process. Each process starts with one default thread called the main thread.

Killing a thread via its parent process may mean that you will want to first create a new process in which to house any new threads that you may wish to forcefully terminate. This is to avoid terminating the main process.

There are two main approaches to killing a thread’s parent process, they are:

Let’s take a look at each in turn.

Killing a Process With Code

A process can be killed by calling the terminate() or kill() methods on the multiprocessing.Process instance.

Читайте также:  Html css background image as link

Each process in python has a corresponding instance of the multiprocessing.Process class.

Источник

How to Close a Thread in Python

You can close a new thread by returning from run() or raising an exception.

In this tutorial you will discover how to close a thread in Python.

Need to Close a Thread

A thread is a thread of execution in a computer program.

Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create additional threads in our program in order to execute code concurrently.

Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.

You can learn more about Python threads in the guide:

While executing a function in a new thread we may need to stop the thread immediately.

This could be for many reasons, such as:

  • Based on a condition or state within the application.
  • A dependent resource is no longer available.
  • The user requests the program be closed.

How can we close a new thread immediately?

Run your loops using all CPUs, download my FREE book to learn how.

How to Close a New Thread

A new thread will close when the run() function of the threading.Thread class returns.

This can happen in one of two ways:

  • The run() function returns normally.
  • The run() function raises an uncaught error or exception.

We can return or raise an uncaught exception to close a thread, and this can be implemented in a few ways, such as:

  1. Call return from a target task function.
  2. Call system.exit().
  3. Raise an Error or Exception.

Let’s take a closer look at each.

Approach 1. Close Thread By Return

The run() function of the threading.Thread class will execute our target function in a new thread of execution.

Consider the case where we create a new thread and configure it to execute a custom task() function via the “target” argument. The thread is then started by calling the start() function.

In this case, the start() function executes the run() function of the threading.Thread class in a new thread and returns immediately.

The run() function of the threading.Thread class will call our task() function. Our task function will return eventually, then the run function will return and the thread will terminate.

This is the normal usage of a thread.

We can choose to close the thread any time from within our task function.

This can be achieved by returning from the task function.

This will terminate the thread.

The trigger to close the thread may come from another thread, such as a boolean variable or an event.

You can learn more about triggering a thread to stop from another thread in this tutorial:

Approach 2. Close Thread By sys.exit()

Another approach is to call the sys.exit() function at any point within our task() function or in the functions it calls.

This will raise a SystemExit exception which will not be caught and will terminate the new thread.

Читайте также:  Java get task list

This approach is helpful if we are deep down the call-graph of custom functions and the return statement is not convenient.

Approach 3. Close Thread By Exception

Another approach is to raise an Error or Exception in the target function or any called function.

If the Error or Exception is uncaught it will unravel the call graph of the thread, then terminate the thread.

The downside of this approach is that the default handler for uncaught exceptions will report the exception to the terminal. This can be changed by specifying a handler via threading.excepthook.

You can learn more about unhandled exceptions in threads here:

Now that we know how to close a thread from within the thread, let’s look at some worked examples.

Confused by the threading module API?
Download my FREE PDF cheat sheet

Close Thread By Returning

We can close a thread by returning from the run function at any time.

This can be achieved by using the “return” statement in our target task function.

If the threading.Thread class has been extended and the run() function overridden, then the “return” statement can be used in the run() function directly.

We can demonstrate this with a worked example.

In this example, we will have a task that loops forever. Each iteration, it will generate a random number between 0 and 1, report the value then sleep for a fraction of a second. If the generated value is greater than 0.9, then the thread will choose to close immediately.

The task() function below implements this.

Источник

Threading, как закрыть поток на Python?

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

Note:
Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

Поэтому точно так-же, как и в скрытом смысле этой цитаты, советую ознакомиться с классом Event.

kshnkvn

import time from threading import Thread stop = False def some_thread(): while not stop: print(stop) time.sleep(0.5) if __name__ == "__main__": some_task = Thread(target=some_thread) some_task.start() time.sleep(2) stop = True some_task.join()

Не до конца понимаю как это можно сделать в моем случае, мне нужно остановить поток, при этом чтобы dg.py дальше работал, можете помочь?

. from dragonbot import dg def start_thread(kit,user_token): global thread try: t = threading.Thread(target=load_kit, name= 'Поток <>'.format(thread), args=('<>'.format(kit),'<>'.format(user_token))) thread = thread + 1 t.start() print(t) send_vk("📌Поток удачно запущен",16736) except: send_vk() def load_kit(kit,token): p = dg(token) if kit == 'full': asyncio.run(p.full()) elif kit == 'aver': asyncio.run(p.aver()) elif kit == 'mini': asyncio.run(p.mini()) if __name__ == '__main__': thread = 0 start_thread("mini","hdhudgv")
class dg(object): def __init__(self, token): self.vk_session = vk_api.VkApi(token=token) self.vk = self.vk_session.get_api() #Тут остальные функции async def mini(self): task_race = asyncio.create_task(self.race(0)) task_business = asyncio.create_task(self.business(60)) task_mining = asyncio.create_task(self.mining(180)) task_job = asyncio.create_task(self.job(360)) await asyncio.gather(task_race, task_business, task_mining, task_job)

Источник

Оцените статью