private:
string container_;
string name_;
+ mutex mutex_;
+ Tensor resource_ GUARDED_BY(mutex_);
+ std::atomic<bool> initialized_{false};
};
// Registers a kernel for an op which produces a handle to a resource of the
template <typename T>
void ResourceHandleOp<T>::Compute(OpKernelContext* ctx) {
- Tensor* output = nullptr;
- OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output));
- output->scalar<ResourceHandle>()() =
- MakeResourceHandle<T>(ctx, container_, name_);
+ if (!initialized_.load()) {
+ mutex_lock ml(mutex_);
+ AllocatorAttributes attr;
+ attr.set_on_host(true);
+ OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_RESOURCE, TensorShape({}),
+ &resource_, attr));
+ resource_.scalar<ResourceHandle>()() =
+ MakeResourceHandle<T>(ctx, container_, name_);
+ initialized_.store(true);
+ }
+ ctx->set_output(0, resource_);
}
} // end namespace tensorflow