class HDF5Dataset(Dataset):
    """
    Args:
        h5data (HDF5 dataset): HDF5 dataset object
    """
    def __init__(self, h5data_file):
        self.h5data_file = h5data_file
        
    def __getitem__(self, index):
        return self.h5data[index, ...]

    def __len__(self):
        return len(self.h5data)

    def h5py_worker_init(self):
        self.h5data = h5py.File(self.h5data_file, "r", libver="latest", swmr=True)
        atexit.register(self.cleanup)

    def cleanup(self):
        self.h5data.close()

def worker_init_fn(worker_id):
    worker_info = torch.utils.data.get_worker_info()
    dataset = worker_info.dataset
    dataset.h5py_worker_init()


dataset = HDF5Dataset("Mydata.h5")
DataLoader(dataset, batch_size=4, num_workers=4, worker_init_fn=worker_init_fn)