Is there a form to draw the background with concurrent programming in Pygame?

I am developing a videogame in python with pygame and I want to draw the scenary using my function “draw” and concurrent programming to optimize it and use a thread to manage the drawing throughout the run. I used ThreadPoolExecutor to can re-use a thread, but the drawing is very bad because sometimes the backgroung is behind the player(the square) and sometimes it is in front of the player.

import sys
import pygame
import threading
from concurrent.futures import ThreadPoolExecutor


pygame.init()

# ----------------------------------------
#                 Variables
# ----------------------------------------

width = 600
height = 600

square = pygame.Rect(100,100,100,100)

surface = pygame.display.set_mode( (width, height) )

executor = ThreadPoolExecutor(max_workers=1)

pygame.display.set_caption('Texto')

font = pygame.font.SysFont("arial", 24)


# ----------------------------------------
#                 Function
# ----------------------------------------


def draw():

    surface.fill((20, 210, 190))


# ----------------------------------------
#                   Loop
# ----------------------------------------


while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    executor.submit(draw)
    pygame.draw.rect(surface,(100,100,100),square)

    pygame.display.update()

How can I do to have the background behind the player and do it re-using a thread to optimize it?

Answer

You must do all the drawing in a single thread. There is not any benefit of drawing the background in a different thread. They cannot guarantee the order of execution between different threads.

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    surface.fill((20, 210, 190))
    pygame.draw.rect(surface,(100,100,100),square)
    pygame.display.update()

It is common for all graphics pipe operations to be performed on a single thread. Whereas the game logic can be done in a different thread.
With pygame, you also need to handle the events on the main thread (see pygame.event.get() not returning any events when inside a thread).