当python使用多进程或协同程序时会发生竞争条件吗?

时间:2018-04-23 02:06:00

标签: python multiprocessing openstack coroutine

我现在正在攻击Nova代码,我发现Nova使用oslo_concurrency lockutils作为像@utils.synchronized(cell_mapping.uuid)这样的装饰器。例如

def set_target_cell(context, cell_mapping):
"""Adds database connection information to the context
for communicating with the given target_cell.

This is used for permanently targeting a cell in a context.
Use this when you want all subsequent code to target a cell.

Passing None for cell_mapping will untarget the context.

:param context: The RequestContext to add connection information
:param cell_mapping: An objects.CellMapping object or None
"""

global CELL_CACHE
if cell_mapping is not None:
    # avoid circular import
    from nova import db
    from nova import rpc

    # Synchronize access to the cache by multiple API workers.
    @utils.synchronized(cell_mapping.uuid)
    def get_or_set_cached_cell_and_set_connections():
        try:
            cell_tuple = CELL_CACHE[cell_mapping.uuid]
        except KeyError:
            db_connection_string = cell_mapping.database_connection
            context.db_connection = db.create_context_manager(
                db_connection_string)
            if not cell_mapping.transport_url.startswith('none'):
                context.mq_connection = rpc.create_transport(
                    cell_mapping.transport_url)
            CELL_CACHE[cell_mapping.uuid] = (context.db_connection,
                                             context.mq_connection)
        else:
            context.db_connection = cell_tuple[0]
            context.mq_connection = cell_tuple[1]

    get_or_set_cached_cell_and_set_connections()
else:
    context.db_connection = None
    context.mq_connection = None

上面的代码使用@utils.synchronized(cell_mapping.uuid),我很困惑为什么它在这里使用lock来同步全局CELL_CACHE。

我认为Nova代码只使用协同程序和进程。

协同程序不会导致竞争条件对吗?由于协程上下文切换不受OS系统控制。

该进程使用OS系统来控制上下文切换,但每个进程都有自己的内存地址,每个进程不共享全局变量,因此它不应该有任何竞争条件吗?

那么为什么它在这里使用锁同步?

我认为有什么不对吗?请提前帮助,谢谢。

0 个答案:

没有答案