Is it possible to run two "while 1:" loops in two threadings respectively?
Diez B. Roggisch
deets at nospam.web.de
Tue Jul 17 03:01:36 EDT 2007
zxo102 schrieb:
> Hi,
> I would like to combine two python applications into a single one
> with two threadings. Both of them have a "while 1:" loop respectively.
> For example, one application is to monitoring serial port 'com1' and
> another application is a TCP/IP server which has used threadings
> already. I write the following demo code but it does not work right.
> It stays in the first "while 1:" and never thingOne.start(). The
> second threading never be started.
> Any ideas?
>
> Thanks a lot.
>
> Ouyang
> #################################################################
> import threading, time
> class serial_port_com1:
> def spc(self):
> i = 0
> while 1:
> time.sleep(5)
> print "%d: hello, I am here in spc()"%i
> i += 1
>
> class TCP_IP:
> def tcpip(self):
> i = 0
> while 1:
> time.sleep(5)
> print "%d: hello, I am here in tcpip()"%i
> i += 1
>
> class ThreadOne ( threading.Thread ):
> def run ( self ):
> print 'Thread', self.getName(), 'started.'
> time.sleep ( 5 )
> print 'Thread', self.getName(), 'ended.'
>
> class ThreadTwo ( threading.Thread ):
> def run ( self ):
> print 'Thread', self.getName(), 'started.'
> thingOne.join()
> print 'Thread', self.getName(), 'ended.'
>
> if __name__=="__main__":
> spc = serial_port_com1()
> tcpip = TCP_IP()
> thingOne = ThreadOne(target=spc.spc())
> thingOne.start()
> thingTwo = ThreadTwo(target=tcpip.tcpip())
> thingTwo.start()
>
There are several problems here. First of all, one either subclasses
Thread and implements run - then your code should look like this:
class ThreadTwo(Thread):
def run(self):
tcpip.tcpip()
Or you don't subclass Thread and pass a target. But that target must be
a function. You don't pass a function, you call it!!
Look at this:
Thread(target=tcpip.tcpip)
Note the missing parentheses!
Apart from that, you should seriously consider applying a consistent
naming style to your code.
Diez
More information about the Python-list
mailing list