Python Forum

Full Version: sending data to thread
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hey, I'm trying to plot multiple graphs at the same time by threading, but I have one constraint all my data comes in one line eg: 11212 11131 313131. In this example, I would have to create 3 graphs simultaneously which I am doing like this:
for i in range(NumberOfDataPoints):
            Thread(target = graph()).start()
 

Graph is just a class declared like this: class graph(): ... (functions in class). The problem is that I don't know how to tell the graph thread that it is supposed to plot the first set of numbers or whichever set. The rest of my script only gets the lines of numbers, adds the time (with datetime.datetime.now()) and saves each line to a line in a txt file it creates. Ideally, I'd like to send the data and time to graph() as I save the file, but I don't know how. one workaround that I've tried is as the graphs are being opened by the code above the graph() class saves the value for I as graphNumber (graphNumber = i) and opens the txt file with all the saved data, but when I try to read LineInTextWithDataPoint[ StartOfFirstSet [ EndOfFirstSet ] I get a list index is out of range error( and for some odd reason when I copy and paste the code directly to python's interpreter it works perfectly ).

In the end, my questions are: is there some way to send data, and read it, to a thread like SendToThread( data, thread_number ) and if that is not possible or easily implemented is there a way for the thread itself detect if it was the first, second, nth thread created>
The easiest way is to define a function that will be the core of your thread, then create threads that will call this function and pass it different arguments (names in example below, graph number for you):

import threading,time,random

RUNS=4
THREADNAMES=['ONE','TWO','THREE']

def threadFunction(id):
    print "Starting thread %s" % id
    for _ in range(RUNS):
        time.sleep(random.uniform(.5,2.5))
        print 'Thread %s still alive' % id
    print "Ending thread %s" % id


# create the threads
threads=[threading.Thread(target=threadFunction,args=(id,)) for id in THREADNAMES]
         
# make them run         
for t in threads:
    t.start()
    
# make sure they are all ended before existing:
for t in threads:
    t.join()
However, due to the Global Interpreter Lock there is no real concurrent execution of threads in Python, so you won't run on more core with Python threading.