Question

How can I use threading in order to run 2 processes simultaneously infinitely? I have a chat program, and I want to input while having stuff print out.

I have done a bit of research into thread, and it seems really complicated. What I have so far is

t = Thread(target=refresh)    
t.daemon = True
t.start()

I have a refresh() function.

But I'm pretty sure this is wrong, and I have no idea how to run this infinitely alongside my input. Can someone explain how threading works, and how I can run it infinitely alongside another infinite loop?

Was it helpful?

Solution

You have to start your thread like you did it in your code. The important thing is to wait for the thread to complete (even if it infinite loop) because without it, you program will stop immediatly. Just use

t.join()

And you code will run until t thread is over. If you want two thread, just do like this

t1.start()
t2.start()

t1.join()
t2.join()

And your two thread will run simultanously

For your crash problem, with multithreading, you have to look at Mutex for the IOerror

OTHER TIPS

#!/usr/bin/python

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

The result of that is:

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

From:http://www.tutorialspoint.com/python/python_multithreading.htm

From there you can figure out how to talk between threads and such.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top