Python Threading loop

Python Threading loop

Content Index :

Python Threading loop
Tag : python , By : adbanginwar
Date : November 28 2020, 09:01 AM

seems to work fine There are several problems with this.
The count and course variables are only in the run function, so they are local to that function only. This means that threads are not sharing this information. The solution: move them outside so that they are class variables (that is, they are now Students.count and Students.course). Your print statements are a bit messed up. Using print(a,b,c,...) will print each of a,b,c,... on a separate line. The solution, enclose the thread's name and course number in a tuple and modify the format string slightly. course =+ 1 would've set course to 1 (because it's the same thing as course = +1) had that part of the if statement ever been executed (which it wasn't because of problem #1). Solution: flip the =+ so that it's course += 1. count += 1 only happens when count is 20. You want this in the else part of the if statement. Also, in the then part, add the the line count = 0 to reset the count. Because these threads are running asynchronously, it can and does happen that count will go from 19 to 21 before you check if count == 20. Fixing this requires somewhat more advanced thread handling.
import random, time
from threading import Thread

class Students(Thread):
    ''' Represents a sleepy thread.'''
    count = 1
    course = 1

    def __init__(self, number, sleepMax):
        ''' Creates a thread with a given Name
        and a random sleep interval less than the maximum. '''
        Thread.__init__(self, name = "Student " + str(number))
        self._RequestInterval = random.randint(1, sleepMax)

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''
        print(" %s, Awaiting Request: %d seconds" % \
              ( self.getName(), self._RequestInterval))
        if Students.count >= 20:
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            print("Class", Students.course, "has reached it limit!")
            Students.course += 1
            Students.count = 0
            #print("Class ", course, " is full.")
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            Students.count += 1

def main():
    ''' Creates the user's number of threads with sleep
    interval less than the user's maximum. Then start
    the threads'''

    NumberOfStudents = 100
    RequestTimer = 5    
    threadList = []
    for count2 in range(NumberOfStudents):
        threadList.append(Students(count2 + 1, RequestTimer))
    for thread in threadList: thread.start()


No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Python threading in for loop

Tag : python , By : RichAA
Date : March 29 2020, 07:55 AM
wish helps you Here is a simple Sublime Text 2 plugin with threading. What it does is insert Hello World! after 3 seconds. What you'll notice is that you can still move the cursor during those three seconds.
In your case, it looks like you just need to grab a bunch of snippets from an API and create a context menu from the returned data. Then there will be a notification at the bottom telling you how many snippets were added. I could be wrong, but you should be able to modify this code to make your plugin work.
import threading
import time
import sublime
import sublime_plugin

The command just creates and runs a thread.
The thread will do all the work in the background.

Note that in your Thread constructor, you will need to pass in an 
instance of your Command class to work with in your thread.
class ExampleCommand(sublime_plugin.TextCommand):

    def run(self, edit):

        exampleThread = ExampleThread(self, edit)

Extend the Thread class and add your functionality in 
the run method below.

One thing to remember when moving your code over is 
you need to use self.cmd instead of self.
class ExampleThread(threading.Thread):

    Remember to pass in the parameters you need
    in this thread constructor.
    def __init__(self, cmd, edit):
        self.cmd = cmd
        self.edit = edit

    Add your functionality here.

    If you need to access the main thread, you need to
    use sublime.set_timeout(self.callback, 1).

    In my example here, you can't call insert text into the editor
    unless you are in the main thread.

    Luckily that is fast operation.

    Basically, time.sleep(3) is a slow operation and will block, hence it
    is run in this separate thread.
    def run(self):
        sublime.set_timeout(self.callback, 1)

    This is the callback function that will be called to 
    insert HelloWorld. 

    You will probably need to use this to set your status message at 
    the end. I'm pretty sure that requires that you be on main thread 
    to work.
    def callback(self):
        self.cmd.view.insert(self.edit, 0, "Hello, World!")
import threading
import time
import sublime
import sublime_plugin

def buildsnippetURL():
    return ""

def getsnippets(snippet_url):
    return ""

class SyncsnippetsCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        syncsnippetsThread = SyncsnippetsThread(self, edit)

class SyncsnippetsThread(threading.Thread):
    def __init__(self, cmd, edit):
        self.cmd = cmd
        self.edit = edit

    def buildLexerDict(self,snippets):
        lexers = snippets[0]['user']['lexers']
        lexer_dict = {}
        for lexer in lexers:
            lexer_dict[lexer] = []
        return lexer_dict

    def buildsnippetsContextDict(self,snippets,lexer_dict):
        snippets_dict = lexer_dict
        for snippet in snippets:
        return snippets_dict

    def run(self): 
        snippet_url = buildsnippetURL()
        snippets_count = 1;
        snippets = getsnippets(snippet_url)

        context_menu = '['
        context_menu += '\n\t{ "caption": "snippets", "id": "file", "children":'
        context_menu += '\n\t\t['
        if snippets == None:
            {"caption":"No snippets available"}
            snippets = snippets['objects']
            lexers = self.buildLexerDict(snippets)
            snippets_dict = self.buildsnippetsContextDict(snippets, lexers)
            for j,key in reversed(list(enumerate(reversed(snippets_dict.keys())))):
                ... loop through JSON and create menu ...
                if j == 0:
                    context_menu += ''
                    context_menu += ',' 
        context_menu += '\n\t\t]'
        context_menu += '\n\t}'
        context_menu += '\n]'
        f = open(sublime.packages_path() + '\snippetSync\\Context.sublime-menu', 'w')

        sublime.set_timeout(lambda: self.callback(snippets_count), 1)

    def callback(self, snippets_count):
        self.cmd.view.set_status('snippet', 'snippet Sync: Added ' + str(snippets_count)  + ' snippets from your account.')
        sublime.set_timeout(lambda: self.cmd.view.erase_status('snippet'), 3000)

python - multi-threading in a for loop

Tag : python , By : Kyle
Date : March 29 2020, 07:55 AM
With these it helps Here is a slightly modified version using a semaphore object
import threading
import Queue

NUM_THREADS = 2 # you can change this if you want

semaphore = threading.Semaphore(NUM_THREADS)

threads = NUM_THREADS

running_threads = []

lock = threading.Lock()

q = Queue.Queue()

# moved the check function out of the loop
def check(name, q, s):
    # acquire the semaphore
    with s:
        not_empty = True

        while not_empty:

                email = q.get(False) # we are passing false so it won't block.
            except Queue.Empty, e:
                not_empty = False


            print email, name, threading.active_count()


            # additional work ...


for x in open(names):
    name = x.strip()

    for word in open(emails):

    for i in range(threads):
            t = threading.Thread(target=check, args=(name, q, semaphore))
            # t.setDaemon(True) # we are not setting the damenon flag


    # joining threads (we need this if the daemon flag is false)
    for t in running_threads:

    # joining queue (Probably won't need this if the daemon flag is false)

Threading / While Loop with python

Tag : python , By : Jesenko Mehmedbasic
Date : March 29 2020, 07:55 AM
To fix the issue you can do How do you know it runs only once? Have you debugged it or do you expect to have the correct result when code reaches this part?
with open('datafile.csv', 'r') as fp:
#Parse the xml
   _t = threading.Timer(5.0, parseXML)
   _t.daemon = True
   with urllib.request.urlopen(....)
foo = threading.Lock()

with foo:
    with open(...) as fp:

Python threading outperforms simple while loop OR threading Optimization

Tag : python , By : turret
Date : March 29 2020, 07:55 AM

Python threading in a loop but with max threads

Tag : python , By : Xander
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com