We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Concurrent imports cause error in force_pydevd 
Happened in Flask multiproc test on macOS, but I think it can potentially occur in any scenario where a module is imported concurrently from another thread:
```
I+05.947: Debuggee-86 stderr:
          b'Error on request:\n'
          b'Traceback (most recent call last):\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/werkzeug/serving.py", line 304, in run_wsgi\n'
          b'    execute(self.server.app)\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/werkzeug/serving.py", line 292, in execute\n'
          b'    application_iter = app(environ, start_response)\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise\n'
          b'    raise value\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/tests/test_data/flask1/__init__.py", line 1, in <module>\n'
          b'    import debug_me  # noqa\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/tests/DEBUGGEE_PYTHONPATH/debug_me/__init__.py", line 49, in <module>\n'
          b'    import ptvsd.server\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/server/__init__.py", line 9, in <module>\n'
          b'    import ptvsd._vendored.force_pydevd  # noqa\n'
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/_vendored/force_pydevd.py", line 14, in <module>\n'
          b"    prefix_matcher('pydev', '_pydev'))\n"
          b'  File "/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/_vendored/__init__.py", line 101, in check_modules\n'
          b'    for modname, mod in sys.modules.items():\n'
          b'RuntimeError: dictionary changed size during iteration\n'
```
It needs to take a snapshot of the module list before iterating.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/ptvsd/_vendored/__init__.py`
Content:
```
1 # Copyright (c) Microsoft Corporation. All rights reserved.
2 # Licensed under the MIT License. See LICENSE in the project root
3 # for license information.
4 
5 from __future__ import absolute_import, division, print_function, unicode_literals
6 
7 import contextlib
8 from importlib import import_module
9 import os
10 import sys
11 
12 from . import _util
13 
14 
15 VENDORED_ROOT = os.path.dirname(os.path.abspath(__file__))
16 # TODO: Move the "pydevd" git submodule to the ptvsd/_vendored directory
17 # and then drop the following fallback.
18 if 'pydevd' not in os.listdir(VENDORED_ROOT):
19     VENDORED_ROOT = os.path.dirname(VENDORED_ROOT)
20 
21 
22 def list_all(resolve=False):
23     """Return the list of vendored projects."""
24     # TODO: Derive from os.listdir(VENDORED_ROOT)?
25     projects = [
26         'pydevd',
27     ]
28     if not resolve:
29         return projects
30     return [project_root(name) for name in projects]
31 
32 
33 def project_root(project):
34     """Return the path the root dir of the vendored project.
35 
36     If "project" is an empty string then the path prefix for vendored
37     projects (e.g. "ptvsd/_vendored/") will be returned.
38     """
39     if not project:
40         project = ''
41     return os.path.join(VENDORED_ROOT, project)
42 
43 
44 def iter_project_files(project, relative=False, **kwargs):
45     """Yield (dirname, basename, filename) for all files in the project."""
46     if relative:
47         with _util.cwd(VENDORED_ROOT):
48             for result in _util.iter_all_files(project, **kwargs):
49                 yield result
50     else:
51         root = project_root(project)
52         for result in _util.iter_all_files(root, **kwargs):
53             yield result
54 
55 
56 def iter_packaging_files(project):
57     """Yield the filenames for all files in the project.
58 
59     The filenames are relative to "ptvsd/_vendored".  This is most
60     useful for the "package data" in a setup.py.
61     """
62     # TODO: Use default filters?  __pycache__ and .pyc?
63     prune_dir = None
64     exclude_file = None
65     try:
66         mod = import_module('._{}_packaging'.format(project), __name__)
67     except ImportError:
68         pass
69     else:
70         prune_dir = getattr(mod, 'prune_dir', prune_dir)
71         exclude_file = getattr(mod, 'exclude_file', exclude_file)
72     results = iter_project_files(
73         project,
74         relative=True,
75         prune_dir=prune_dir,
76         exclude_file=exclude_file,
77     )
78     for _, _, filename in results:
79         yield filename
80 
81 
82 def prefix_matcher(*prefixes):
83     """Return a module match func that matches any of the given prefixes."""
84     assert prefixes
85 
86     def match(name, module):
87         for prefix in prefixes:
88             if name.startswith(prefix):
89                 return True
90         else:
91             return False
92     return match
93 
94 
95 def check_modules(project, match, root=None):
96     """Verify that only vendored modules have been imported."""
97     if root is None:
98         root = project_root(project)
99     extensions = []
100     unvendored = {}
101     for modname, mod in sys.modules.items():
102         if not match(modname, mod):
103             continue
104         if not hasattr(mod, '__file__'):  # extension module
105             extensions.append(modname)
106         elif not mod.__file__.startswith(root):
107             unvendored[modname] = mod.__file__
108     return unvendored, extensions
109 
110 
111 @contextlib.contextmanager
112 def vendored(project, root=None):
113     """A context manager under which the vendored project will be imported."""
114     if root is None:
115         root = project_root(project)
116     # Add the vendored project directory, so that it gets tried first.
117     sys.path.insert(0, root)
118     try:
119         yield root
120     finally:
121         sys.path.remove(root)
122 
123 
124 def preimport(project, modules, **kwargs):
125     """Import each of the named modules out of the vendored project."""
126     with vendored(project, **kwargs):
127         for name in modules:
128             import_module(name)
129
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/ptvsd/_vendored/__init__.py b/src/ptvsd/_vendored/__init__.py
--- a/src/ptvsd/_vendored/__init__.py
+++ b/src/ptvsd/_vendored/__init__.py
@@ -98,7 +98,7 @@
         root = project_root(project)
     extensions = []
     unvendored = {}
-    for modname, mod in sys.modules.items():
+    for modname, mod in list(sys.modules.items()):
         if not match(modname, mod):
             continue
         if not hasattr(mod, '__file__'):  # extension module

{"golden_diff": "diff --git a/src/ptvsd/_vendored/__init__.py b/src/ptvsd/_vendored/__init__.py\n--- a/src/ptvsd/_vendored/__init__.py\n+++ b/src/ptvsd/_vendored/__init__.py\n@@ -98,7 +98,7 @@\n         root = project_root(project)\n     extensions = []\n     unvendored = {}\n-    for modname, mod in sys.modules.items():\n+    for modname, mod in list(sys.modules.items()):\n         if not match(modname, mod):\n             continue\n         if not hasattr(mod, '__file__'):  # extension module\n", "issue": "Concurrent imports cause error in force_pydevd \nHappened in Flask multiproc test on macOS, but I think it can potentially occur in any scenario where a module is imported concurrently from another thread:\r\n```\r\nI+05.947: Debuggee-86 stderr:\r\n          b'Error on request:\\n'\r\n          b'Traceback (most recent call last):\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/werkzeug/serving.py\", line 304, in run_wsgi\\n'\r\n          b'    execute(self.server.app)\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/werkzeug/serving.py\", line 292, in execute\\n'\r\n          b'    application_iter = app(environ, start_response)\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/flask/_compat.py\", line 36, in reraise\\n'\r\n          b'    raise value\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/tests/test_data/flask1/__init__.py\", line 1, in <module>\\n'\r\n          b'    import debug_me  # noqa\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/tests/DEBUGGEE_PYTHONPATH/debug_me/__init__.py\", line 49, in <module>\\n'\r\n          b'    import ptvsd.server\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/server/__init__.py\", line 9, in <module>\\n'\r\n          b'    import ptvsd._vendored.force_pydevd  # noqa\\n'\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/_vendored/force_pydevd.py\", line 14, in <module>\\n'\r\n          b\"    prefix_matcher('pydev', '_pydev'))\\n\"\r\n          b'  File \"/Users/runner/runners/2.159.2/work/1/s/.tox/py37/lib/python3.7/site-packages/ptvsd/_vendored/__init__.py\", line 101, in check_modules\\n'\r\n          b'    for modname, mod in sys.modules.items():\\n'\r\n          b'RuntimeError: dictionary changed size during iteration\\n'\r\n```\r\nIt needs to take a snapshot of the module list before iterating.\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport contextlib\nfrom importlib import import_module\nimport os\nimport sys\n\nfrom . import _util\n\n\nVENDORED_ROOT = os.path.dirname(os.path.abspath(__file__))\n# TODO: Move the \"pydevd\" git submodule to the ptvsd/_vendored directory\n# and then drop the following fallback.\nif 'pydevd' not in os.listdir(VENDORED_ROOT):\n    VENDORED_ROOT = os.path.dirname(VENDORED_ROOT)\n\n\ndef list_all(resolve=False):\n    \"\"\"Return the list of vendored projects.\"\"\"\n    # TODO: Derive from os.listdir(VENDORED_ROOT)?\n    projects = [\n        'pydevd',\n    ]\n    if not resolve:\n        return projects\n    return [project_root(name) for name in projects]\n\n\ndef project_root(project):\n    \"\"\"Return the path the root dir of the vendored project.\n\n    If \"project\" is an empty string then the path prefix for vendored\n    projects (e.g. \"ptvsd/_vendored/\") will be returned.\n    \"\"\"\n    if not project:\n        project = ''\n    return os.path.join(VENDORED_ROOT, project)\n\n\ndef iter_project_files(project, relative=False, **kwargs):\n    \"\"\"Yield (dirname, basename, filename) for all files in the project.\"\"\"\n    if relative:\n        with _util.cwd(VENDORED_ROOT):\n            for result in _util.iter_all_files(project, **kwargs):\n                yield result\n    else:\n        root = project_root(project)\n        for result in _util.iter_all_files(root, **kwargs):\n            yield result\n\n\ndef iter_packaging_files(project):\n    \"\"\"Yield the filenames for all files in the project.\n\n    The filenames are relative to \"ptvsd/_vendored\".  This is most\n    useful for the \"package data\" in a setup.py.\n    \"\"\"\n    # TODO: Use default filters?  __pycache__ and .pyc?\n    prune_dir = None\n    exclude_file = None\n    try:\n        mod = import_module('._{}_packaging'.format(project), __name__)\n    except ImportError:\n        pass\n    else:\n        prune_dir = getattr(mod, 'prune_dir', prune_dir)\n        exclude_file = getattr(mod, 'exclude_file', exclude_file)\n    results = iter_project_files(\n        project,\n        relative=True,\n        prune_dir=prune_dir,\n        exclude_file=exclude_file,\n    )\n    for _, _, filename in results:\n        yield filename\n\n\ndef prefix_matcher(*prefixes):\n    \"\"\"Return a module match func that matches any of the given prefixes.\"\"\"\n    assert prefixes\n\n    def match(name, module):\n        for prefix in prefixes:\n            if name.startswith(prefix):\n                return True\n        else:\n            return False\n    return match\n\n\ndef check_modules(project, match, root=None):\n    \"\"\"Verify that only vendored modules have been imported.\"\"\"\n    if root is None:\n        root = project_root(project)\n    extensions = []\n    unvendored = {}\n    for modname, mod in sys.modules.items():\n        if not match(modname, mod):\n            continue\n        if not hasattr(mod, '__file__'):  # extension module\n            extensions.append(modname)\n        elif not mod.__file__.startswith(root):\n            unvendored[modname] = mod.__file__\n    return unvendored, extensions\n\n\n@contextlib.contextmanager\ndef vendored(project, root=None):\n    \"\"\"A context manager under which the vendored project will be imported.\"\"\"\n    if root is None:\n        root = project_root(project)\n    # Add the vendored project directory, so that it gets tried first.\n    sys.path.insert(0, root)\n    try:\n        yield root\n    finally:\n        sys.path.remove(root)\n\n\ndef preimport(project, modules, **kwargs):\n    \"\"\"Import each of the named modules out of the vendored project.\"\"\"\n    with vendored(project, **kwargs):\n        for name in modules:\n            import_module(name)\n", "path": "src/ptvsd/_vendored/__init__.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport contextlib\nfrom importlib import import_module\nimport os\nimport sys\n\nfrom . import _util\n\n\nVENDORED_ROOT = os.path.dirname(os.path.abspath(__file__))\n# TODO: Move the \"pydevd\" git submodule to the ptvsd/_vendored directory\n# and then drop the following fallback.\nif 'pydevd' not in os.listdir(VENDORED_ROOT):\n    VENDORED_ROOT = os.path.dirname(VENDORED_ROOT)\n\n\ndef list_all(resolve=False):\n    \"\"\"Return the list of vendored projects.\"\"\"\n    # TODO: Derive from os.listdir(VENDORED_ROOT)?\n    projects = [\n        'pydevd',\n    ]\n    if not resolve:\n        return projects\n    return [project_root(name) for name in projects]\n\n\ndef project_root(project):\n    \"\"\"Return the path the root dir of the vendored project.\n\n    If \"project\" is an empty string then the path prefix for vendored\n    projects (e.g. \"ptvsd/_vendored/\") will be returned.\n    \"\"\"\n    if not project:\n        project = ''\n    return os.path.join(VENDORED_ROOT, project)\n\n\ndef iter_project_files(project, relative=False, **kwargs):\n    \"\"\"Yield (dirname, basename, filename) for all files in the project.\"\"\"\n    if relative:\n        with _util.cwd(VENDORED_ROOT):\n            for result in _util.iter_all_files(project, **kwargs):\n                yield result\n    else:\n        root = project_root(project)\n        for result in _util.iter_all_files(root, **kwargs):\n            yield result\n\n\ndef iter_packaging_files(project):\n    \"\"\"Yield the filenames for all files in the project.\n\n    The filenames are relative to \"ptvsd/_vendored\".  This is most\n    useful for the \"package data\" in a setup.py.\n    \"\"\"\n    # TODO: Use default filters?  __pycache__ and .pyc?\n    prune_dir = None\n    exclude_file = None\n    try:\n        mod = import_module('._{}_packaging'.format(project), __name__)\n    except ImportError:\n        pass\n    else:\n        prune_dir = getattr(mod, 'prune_dir', prune_dir)\n        exclude_file = getattr(mod, 'exclude_file', exclude_file)\n    results = iter_project_files(\n        project,\n        relative=True,\n        prune_dir=prune_dir,\n        exclude_file=exclude_file,\n    )\n    for _, _, filename in results:\n        yield filename\n\n\ndef prefix_matcher(*prefixes):\n    \"\"\"Return a module match func that matches any of the given prefixes.\"\"\"\n    assert prefixes\n\n    def match(name, module):\n        for prefix in prefixes:\n            if name.startswith(prefix):\n                return True\n        else:\n            return False\n    return match\n\n\ndef check_modules(project, match, root=None):\n    \"\"\"Verify that only vendored modules have been imported.\"\"\"\n    if root is None:\n        root = project_root(project)\n    extensions = []\n    unvendored = {}\n    for modname, mod in list(sys.modules.items()):\n        if not match(modname, mod):\n            continue\n        if not hasattr(mod, '__file__'):  # extension module\n            extensions.append(modname)\n        elif not mod.__file__.startswith(root):\n            unvendored[modname] = mod.__file__\n    return unvendored, extensions\n\n\n@contextlib.contextmanager\ndef vendored(project, root=None):\n    \"\"\"A context manager under which the vendored project will be imported.\"\"\"\n    if root is None:\n        root = project_root(project)\n    # Add the vendored project directory, so that it gets tried first.\n    sys.path.insert(0, root)\n    try:\n        yield root\n    finally:\n        sys.path.remove(root)\n\n\ndef preimport(project, modules, **kwargs):\n    \"\"\"Import each of the named modules out of the vendored project.\"\"\"\n    with vendored(project, **kwargs):\n        for name in modules:\n            import_module(name)\n", "path": "src/ptvsd/_vendored/__init__.py"}]}