原文: https://golangcode.com/run-code-once-with-sync/

---------------------------------------------------

Using a web server as an example, there are multiple stages you can load resources. Within the main() function and within the handler are the obvious two - each with their own advantages and disadvantages. Within the main function can hinder the start-up time of the server, while code within the handler is run on every request.

Sometimes we want to load a resource only once and when it’s first needed. This means it needs to be in the http handler. We have to be careful how we do this though, as each time the handler is called it will be in a separate goroutine. We could use a global variable and if it hasn’t been set (or == nil), load the resource - but this won’t be safe from a concurrency point of view as you could end up running the load sequence twice.

The best way to achieve this is therefore using the sync.Once mutex to efficiently run code once even across goroutines. The example below should demonstrate this.

package main

import (
"fmt"
"sync"
) var doOnce sync.Once func main() {
DoSomething()
DoSomething()
} func DoSomething() {
doOnce.Do(func() {
fmt.Println("Run once - first time, loading...")
})
fmt.Println("Run this every time")
}

Screenshot of without and with the discard option:

Run Code Once on First Load (Concurrency Safe)的更多相关文章

  1. Specifying the Code to Run on a Thread

    This lesson shows you how to implement a Runnable class, which runs the code in its Runnable.run() m ...

  2. Instant Run

    http://tools.android.com/tech-docs/instant-run N Developer Preview users: Instant Run is currently i ...

  3. $( document ).ready()&$(window).load()

    $( document ).ready() https://learn.jquery.com/using-jquery-core/document-ready/ A page can't be man ...

  4. (4)事件处理——(3)代码执行的顺序(Timing of code execution)

    In Chapter 1, Getting Started, we noted that $(document).ready()was jQuery's primary way to perform ...

  5. Run Nutch In Eclipse on Linux and Windows nutch version 0.9

    Running Nutch in Eclipse Here are instructions for setting up a development environment for Nutch un ...

  6. How to Debug Enterprise Portal Code in Dynamics AX 2009

    转载 To set up debugging for pages1. Log into the server that is running the AOS.2. Open the Microsoft ...

  7. Thread的run()与start()的区别

    Java的线程是通过java.lang.Thread类来实现的.VM启动时会有一个由主方法所定义的线程.可以通过创建Thread的实例来创建新的线程.每个线程都是通过某个特定Thread对象所对应的方 ...

  8. Thread’s start method and run method

    工作中用到了Thread,一开始用错了,仔细研究了一下,稍作整理. 前言,今天写代码居然这样写的 new Thread() { @Override public void run() { System ...

  9. 细说OC中的load和initialize方法

    OC中有两个特殊的类方法,分别是load和initialize.本文总结一下这两个方法的区别于联系.使用场景和注意事项.Demo可以在我的Github上找到--load和initialize,如果觉得 ...

随机推荐

  1. consul分布式集群搭建&简单功能测试&故障恢复【h】

    环境准备五台机器: 操作系统 IP Ubuntu 16.04.3 LTS x86_64 192.168.1.185 Ubuntu 16.10 x86_64 192.168.3.152 Ubuntu 1 ...

  2. 第七章 云原生生态的基石 Kubernetes

    7.1 Kubernetes架构 K8s的核心组件: etcd: 协同存储,负责保存整个集群的状态. API:资源操作的唯一入口. controller manager: 维护集群的状态,执行故障检测 ...

  3. 使用mysql连接django时,需要的步骤以及错误解决办法

    django默认使用的sqlite3,更改为SQL时需要按照如下操作进行 1.在settings.py中的78行进行更改 DATABASES = { 'default': { 'ENGINE': 'd ...

  4. scrapy工具创建爬虫工程

    1.scrapy创建爬虫工程:scrapy startproject scrape_project_name >scrapy startproject books_scrapeNew Scrap ...

  5. 《Mysql - Order By 的工作原理?》

    一:概述 - order by 用于 SQL 语句中的排序. - 以  select city,name,age from t where city='杭州' order by name limit ...

  6. SpringBoot中使用@Scheduled创建定时任务

    SpringBoot中使用@Scheduled创建定时任务 定时任务一般会在很多项目中都会用到,我们往往会间隔性的的去完成某些特定任务来减少服务器和数据库的压力.比较常见的就是金融服务系统推送回调,一 ...

  7. Markdown 语法 (转载)

    Markdown 语法整理大集合2017   1.标题 代码 注:# 后面保持空格 # h1 ## h2 ### h3 #### h4 ##### h5 ###### h6 ####### h7 // ...

  8. python 使用API调用和风天气获取天气情况并保存

    第一步.注册注册免费API和阅读技术文档: 注册地址:https://console.heweather.com 注册完成后,激活登录后,新建应用 .新建key KEY名称 密钥ID 密钥 类型下载城 ...

  9. python实战项目 — 爬取中国票房网年度电影信息并保存在csv

    import pandas as pd import requests from bs4 import BeautifulSoup import time def spider(url, header ...

  10. 【Linux】一步一步学Linux——Unix发展史(02)

    目录 00. 目录 01. 请参考Unix传奇 02. 03. 00. 目录 @ 本博客后面会更新 01. 请参考Unix传奇 链接: https://coolshell.cn/articles/23 ...