多线程时循环不运行新变量

时间:2019-04-25 13:21:46

标签: python python-3.x opencv3.0

我目前正在完成我的最后一年大学项目,但我坚持认为是线程问题。我希望能够多次运行我的方法,但是每次运行该方法时,都应该使用新值更新变量。我正在查询API以获取userID,然后通过将其设置为全局变量将其传递到我的main方法中。

def setup():


    try:
        global gun_cascade, camera, frameRate, property_id, length, firstFrame, framecount,i,increment,start_Time,end_Time,statusCopy,userID

        gun_cascade = cv2.CascadeClassifier('cascade.xml')
        camera = cv2.VideoCapture('gun.mp4')
        if camera.isOpened() == False:
            print("Can't open video, isOpened is empty exiting now.")
            exit(0)
        frameRate = camera.get(5)
        property_id = int(cv2.CAP_PROP_FRAME_COUNT)
        length = int(cv2.VideoCapture.get(camera, property_id))

        firstFrame = None
        count = 0
        gun_exist = False
        increment = 0
        start_Time = 0
        end_Time = 0
        i = 0


    except Exception as e:
        print(e)
        exit(0)

上面我将userID设置为global

def decision():
    setup()
    user_object = listener.userIdListner()
    tokenId = user_object.token

    status = user_object.status
    if user_object.status == "ON":
        #status=statusCopy[:]
        #aux = copy.deepcopy(matriz)
        global statusCopy

        statusCopy = copy.deepcopy(tokenId)
        print("About to run mainscrt"+statusCopy)
        #print(type(userID))
        print(type(user_object))

        post_object = listener.mainNullPostMethod()
        post_object.null
        print(post_object.null)
        #opening a a new thread
        Thread(target = main).start()
        #post_object = listener.mainNullPostMethod()
        #post_object.null
        #print(post_object.null)


    else:
        print ("Program failed to run")

在这里,我正在查询我的API以获取userId和状态为开或关。此刻运行良好。但是问题是,如果此方法正在运行,并希望使用新的用户ID再次运行,它会一直运行到'while camera.isOpened():'。到这一点,我不会收到任何错误或任何提示

def main():


    #printing out the userid to see if it's been changed
    userID = statusCopy
    print("The current userID is "+userID)

    while isOpened:


        framecount =0
        framecount += 1
        frameId = camera.get(1) #current frame number

        (grabbed, frame) = camera.read()
        if not grabbed:
            break

        # resize the frame, convert it to grayscale, and blur it
        frame = imutils.resize(frame, width=500)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #gray = cv2.GaussianBlur(gray, (21, 21), 0)

        #gray = cv2.dilate(gray, None, iterations=2)

        #stuff to try in the future
        #scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE, outputRejectLevels = True
        gun = gun_cascade.detectMultiScale(gray, 3,5)

        for (x,y,w,h) in gun:
            randID = uuid.uuid4().hex
            frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
            rects = gun[0]
            neighbours = gun[0]
            weights = gun[0]
           if (frameId % math.floor(frameRate) == 1):
                cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 165, 0), 1)
                cv2.imwrite('bin/' + userID+'-'+randID + '.jpg', frame)
                if userID == "NULL":
                    print("failed due to user null")
                    break
                print("working on pushing images to s3"+userID)
                s3.uploadDirectory("bin/", "open-gun-recordings",userID)

                picURL = "s3bucket.com/users/screenshots/"+userID+'/'+userID+'-'+randID+'.jpg'

                text.fire(picURL)



        cv2.imshow("Security Feed", frame)
        key = cv2.waitKey(1) & 0xFF


    camera.release()
    cv2.destroyAllWindows()

以上,我希望能够同时运行此方法的多个实例,并且每个实例具有不同的userId。

if __name__ == '__main__':
    #mainNullPostMethod()
    #runDecision()
    while True:

        time.sleep(5)
        decision()

任何帮助和建议将不胜感激。我不是最擅长python的人,如果这是一个愚蠢的问题,我深表歉意

1 个答案:

答案 0 :(得分:1)

首先,不要使用全局变量,它们是不好的,因为从多个功能(在您的情况下为多个线程)更改时,as described in this answer会使事情难以跟踪。

我看到的问题是在用于生成线程的userID函数中初始化main,问题是即使您在userID = statusCopy中初始化main ,即使您在decision中使用statusCopy = copy.deepcopy(tokenId)进行了深拷贝,仍然会被所有并发的决策调用全局覆盖。

让我们想象一下您第一次调用decision,初始化userID,然后为main生成一个线程,该线程利用了userID 。现在,我不确定main的执行需要多长时间,但是出于参数考虑,您要使用sleep等待5秒钟,然后再次执行整个操作(第一个线程仍在运行)。现在,您基本上在整个函数链的第二次执行中更改了userID,并且第一个线程开始使用经过修改的userID,根据定义,由于您想使用特定的{{ 1}}信息与您的第一个线程。我建议您将深层副本传递给线程,并在userID中初始化本地userID,以免并发线程更改它。

此外,我不确定您是否要执行main并每5秒刷新一次线程,也许您也应该在此设置限制。