Python Threading: Making the thread function return from an external signal

2024/10/13 17:17:51

Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread.

test27.py

import threading
import timelock = threading.Lock()def Read(x,y):flag = 1while True:lock.acquire()try:z = x+y; w = x-yprint z*wtime.sleep(1)if flag == 0:print "ABORTING"returnfinally:print " SINGLE run of thread executed"lock.release()

test28.py

import time, threadingfrom test27 import Readprint "Hello Welcome"
a = 2; b = 5
t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b))
t.start()
time.sleep(5)
t.flag = 0 # This is not updating the flag variable in Read FUNCTION
t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking.
print "PROGRAM ENDED"
Answer

The Thread class can be instantiated with the target argument. Then you just give it a function which should be executed in a new thread. It is a convenient way to start a simple thread, but for more control it is usually easier to have a class inherited from Thread, which has additional member variables, like the flag for aborting.

For example:

import time
import threadingclass MyThread(threading.Thread):def __init__(self, x, y):super().__init__()# or in Python 2:# super(MyThread, self).__init__()self.x = xself.y = yself._stop_requested = Falsedef run(self):while not self._stop_requested:z = self.x + self.yw = self.x - self.yprint (z * w)time.sleep(1)def stop(self, timeout=None):self._stop_requested = Trueself.join(timeout)

Then, to start the thread, call start() and then to stop it call stop():

>>> def run_thread_for_5_seconds():
...     t = MyThread(3, 4)
...     t.start()
...     time.sleep(5)
...     t.stop()
...
>>> run_thread_for_5_seconds()
-7
-7
-7
-7
-7
>>>
https://en.xdnf.cn/q/118052.html

Related Q&A

Python join data lines together

Hello i have dataset a few thousand lines which is split in even and odd number lines and i cant find a way to join them together again in the same line. Reading the file and overwriting it is fine or …

How to undraw plot with Zelle graphics?

This is a code problem for Python 3.5.2 using John Zelles graphics.py:I have spent a good amount of time looking for the answer here, but just can not figure it out. The function undraw() exists just l…

/bin/sh: line 62: to: command not found

I have a python code in which I am calling a shell command. The part of the code where I did the shell command is:try:def parse(text_list):text = \n.join(text_list)cwd = os.getcwd()os.chdir("/var/…

Using PyMySQL with MariaDB

I have read this article about switching from MySQL to MariaDB on Ubuntu. The article claims that it would be not problem to switch between the two. Currently, I am using PyMySQL to connect to my MySQL…

Overloading str in Python

I have code that looks like the following:class C(str):def __init__(self, a, b):print(init was called!)super().__init__(b)self.a = ac = C(12, c)When I try to run it, it gives me the following error:Tra…

Why cant I install Pillow on my mac? It gives some errors

here is the error from installing Pillow. Im using OS X Mavericks. I tried installing Pillow through pip install.._imaging.c:391:28: warning: implicit conversion loses integer precision: long to int [-…

what on earth the unicode number is?

in python:>>> "\xc4\xe3".decode("gbk").encode("utf-8") \xe4\xbd\xa0 >>> "\xc4\xe3".decode("gbk") u\u4f60we can get two conclusions:1.…

explicitly setting style sheet in python pyqt4?

In pyqt standard way for setting style sheet is like this:MainWindow.setStyleSheet(_fromUtf8("/*\n" "gridline-color: rgb(85, 170, 255);\n" "QToolTip\n" "{\n" &qu…

missing required Charfield in django is saved as empty string and do not raise an error

If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case.models.py:from django.db import modelsclass Essai(models.Model):ch1 =…

Beautiful soup missing some html table tags

Im trying to extract data from a website using beautiful soup to parse the html. Im currently trying to get the table data from the following webpage :link to webpageI want to get the data from the tab…