Python中的多线程应用程序

时间:2018-06-20 09:00:40

标签: python multithreading timer

我在这里拥有一个使用OpenCV用Python开发的应用程序。此应用程序必须从套接字接收视频以及udp消息。我能够接收视频并在视频上显示udp消息。但是由于recv功能的阻塞性,由于udp消息的更新速率较低,因此视频变慢。我想在其他线程(例如使用计时器)中分开接收udp消息,以便将视频和udp消息的读取分开。我试图在视频接收的while循环之外创建一个新函数,但是在while循环中无法访问接收缓冲区。

请大家帮助我使用单独的线程接收视频和udp消息。请修改下面的代码。

enter code here
import numpy as np
import cv2
import socket
import struct
import threading

MCAST_GRP = '226.1.1.1'
MCAST_PORT = 4321

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', MCAST_PORT))  # use MCAST_GRP instead of '' to listen only
                             # to MCAST_GRP, not all groups on MCAST_PORT
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

while(True):
    # this receive has to be seperated into diffrenet independent thread    
    buffer_Raw= sock.recv(50) 

    # Capture frame-by-frame
    ret, frame = cap.read()
    # Display the resulting frame
    font = cv2.FONT_HERSHEY_SIMPLEX

    font                   = cv2.FONT_HERSHEY_SIMPLEX
    bottomLeftCornerOfText = (900,50)
    fontScale              = 1
    fontColor              = (0,0,0)
    lineType               = 2

    cv2.putText(frame,str(buffer_Raw), bottomLeftCornerOfText, font, fontScale, fontColor, lineType)


    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture

cap.release()
cv2.destroyAllWindows()

0 个答案:

没有答案