Errors when using num_workers>0 in DataLoader

Ok, it seems that I have solved the problem, and now I can set the num_workers>0.
What I did was just to insert all the code that train the network in a function: train(), summaring:

def train():
    # Here was inserted the whole code that train the network ...
if __name__ == '__main__':
    train()

Could anyone explain how and why this works?