2017-01-26 71 views
0

我有这个脚本创建一个UDP服务器,它接收一个流并将其放入一个数组中。每分钟后,我都会摄入数据,清理并将其发送到另一台服务器。这两个操作都在共享相同变量的头上运行。避免多线程UDP服务器中的数据丢失

import socket, time, threading, copy 

UDP_IP = "255.255.255.255" 
UDP_PORT = 4032 

store = [] 

lock = threading.Lock() 

def receive_data(): 
    global queue 
    global lock 

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    s.bind((UDP_IP, UDP_PORT)) 

    while True: 
     data = s.recv(9999) 
     # store data temporarily 
     lock.acquire() 
     store.append(data) 
     lock.release() 

def send_data(): 
    global store 
    global lock 

    lock.acquire() 
    data = copy.deepcopy(store) 
    store = [] 
    lock.release() 

    # Clean up, send and put a timer 
    threading.Timer(60, send_data).start() 

t1 = threading.Thread(target=receive_data, name='Server') 
t1.start() 

t2 = threading.Thread(target=send_data, name='Sender') 
t2.start() 

我的问题:这是一个足够好的脚本避免数据丢失?我担心,如果锁定变量可能会使UDP服务器处于保留状态以访问它并以某种方式跳过在此期间发送的数据。

+0

您的代码不显示UDP线程处理锁。它似乎没有等待。 – quamrana

+3

常见模式是使用线程之间共享的队列。队列是线程安全的,所以你所有的发送函数都需要定期检查是否有新的数据并发送它。这意味着在任何函数中都不需要锁定机制。 –

+1

也许你应该使用线程安全的'Queue'。 https://docs.python.org/2/library/queue.html或https://docs.python.org/3.6/library/queue.html –

回答

1

假设你的代码是这样的:

import socket, time, threading, copy 

UDP_IP = "255.255.255.255" 
UDP_PORT = 4032 

store = [] 

lock = threading.Lock() 

def receive_data(): 
    global store 
    global lock 
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    s.bind((UDP_IP, UDP_PORT)) 

    while True: 
     data = s.recv(9999) 
     # store data temporarily 
     lock.acquire() # Note the lock around access to global store 
     store.append(data) 
     lock.release() 

def send_data(): 
    global store 
    global lock 

    lock.acquire() 
    data = store[:] # cheap copy of the contents while locked 
    store = [] 
    lock.release() 

    # Expensive processing of data to send it to another server 
    process(data) 

    # Clean up, send and put a timer 
    threading.Timer(60, send_data).start() 

t1 = threading.Thread(target=receive_data, name='Server') 
t1.start() 

t2 = threading.Thread(target=send_data, name='Sender') 
t2.start() 

则没有敲竹杠只要读取数据关注。无论如何,套接字将为你缓冲数据。

+0

谢谢你的回答... – Daniyal