一段无锁并且可以水平扩展的代码

看到一段代码,如下,开始无法理解这么写的目的,但是仔细一想便明白了作者意思。

def _store_new_measures(self, metric, data):
    tmpfile = self._get_tempfile()
    tmpfile.write(data)
    tmpfile.close()
    path = self._build_measure_path(metric.id, True)
    while True:
        try:
            os.rename(tmpfile.name, path)
            break
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise
            try:
                os.mkdir(self._build_measure_path(metric.id))
            except OSError as e:
                # NOTE(jd) It's possible that another process created the
                # path just before us! In this case, good for us, let's do
                # nothing then! (see bug #1475684)
                if e.errno != errno.EEXIST:
                    raise

代码逻辑可以简单得分解成

1、移动文件,成功则返回。
2、如果失败,则创建目录。回到步骤1

背景部分还有创建的目录可能在其他进程或者线程中被创建和删除。

上面的代码写得还是比较巧妙的,没有线程锁也没有进程锁。只是尝试得去移动文件,直到移动成功。

你可能感兴趣的:(一段无锁并且可以水平扩展的代码)