开发者

My script needs to run two loops at the same time to read IO data from two different sources. Is my threading correct?

import threading
import mynetworking

def FirstNIC():

    for addr in mynetworking.first.scan():
        print addr

def SecondNIC():

    for addr in mynetworking.second.scan():
        print addr

first  = threading.Thread(target=FirstNIC)
second = threading.Thread(target=SecondNIC)

first.start()
second.start()

That's the basic code structure I intend to you. The program will be running two while True loops to read data coming in over two different network sources. The script above needs to collect that data and log it.

Will this code work? Is it any good? Should the threads return the addr for the main program to log? Or should I simply replace print addr with log(addr)?

This is my first time with multithreading so I'm开发者_如何转开发 not entirely sure how this works...


Your code is fine except that your print statments can collide because they could both write at once. Use Queue.queue for easy synchronization:

import threading
import mynetworking
import Queue

def FirstNIC(queue):
    for addr in mynetworking.first.scan(queue):
        queue.put(addr)

def SecondNIC(queue):
    for addr in mynetworking.second.scan():
        queue.put(addr)

def logger(queue):
    while True:
        print queue.get()

output_queue = Queue.queue()
first  = threading.Thread(target=FirstNIC, args=(output_queue,))
second = threading.Thread(target=SecondNIC, args=(output_queue,))

first.start()
second.start()

logger(output_queue)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜