1# Copyright 2015 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""A cache for FileWriters.""" 16 17import threading 18 19from tensorflow.python.framework import ops 20from tensorflow.python.summary.writer.writer import FileWriter 21from tensorflow.python.util.tf_export import tf_export 22 23 24@tf_export(v1=['summary.FileWriterCache']) 25class FileWriterCache(object): 26 """Cache for file writers. 27 28 This class caches file writers, one per directory. 29 """ 30 # Cache, keyed by directory. 31 _cache = {} 32 33 # Lock protecting _FILE_WRITERS. 34 _lock = threading.RLock() 35 36 @staticmethod 37 def clear(): 38 """Clear cached summary writers. Currently only used for unit tests.""" 39 with FileWriterCache._lock: 40 # Make sure all the writers are closed now (otherwise open file handles 41 # may hang around, blocking deletions on Windows). 42 for item in FileWriterCache._cache.values(): 43 item.close() 44 FileWriterCache._cache = {} 45 46 @staticmethod 47 def get(logdir): 48 """Returns the FileWriter for the specified directory. 49 50 Args: 51 logdir: str, name of the directory. 52 53 Returns: 54 A `FileWriter`. 55 """ 56 with FileWriterCache._lock: 57 if logdir not in FileWriterCache._cache: 58 FileWriterCache._cache[logdir] = FileWriter( 59 logdir, graph=ops.get_default_graph()) 60 return FileWriterCache._cache[logdir] 61