Is it possible to run two "while 1:" loops in two threadings respectively?

Discussion in 'Python' started by zxo102, Jul 17, 2007.

  1. zxo102

    zxo102 Guest

    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()
     
    zxo102, Jul 17, 2007
    #1
    1. Advertisements

  2. 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
     
    Diez B. Roggisch, Jul 17, 2007
    #2
    1. Advertisements

  3. zxo102

    zxo102 Guest

    Diez,
    Thanks for your reply. I have tried the both you suggested. First
    one works and second one does not. I am using "subclass thread" way to
    implement my application. Thanks a lot.
    ouyang
     
    zxo102, Jul 19, 2007
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.