当前位置: 首页 > news >正文

怎么用腾讯云服务器做网站廊坊首页霸屏排名优化

怎么用腾讯云服务器做网站,廊坊首页霸屏排名优化,十堰网站建设是什么,做网站开发需要学什么软件文章目录 一、简介二、Context 的基本概念1. context 包常用函数 三、Context 的基本用法1. WithCancel:取消任务的上下文 四、超时控制:WithTimeout 和 WithDeadline1. 使用 WithTimeout 控制任务超时2. 使用 WithDeadline 设定截止时间 五、传递上下文…

文章目录

      • 一、简介
      • 二、Context 的基本概念
        • 1. `context` 包常用函数
      • 三、Context 的基本用法
        • 1. `WithCancel`:取消任务的上下文
      • 四、超时控制:`WithTimeout` 和 `WithDeadline`
        • 1. 使用 `WithTimeout` 控制任务超时
        • 2. 使用 `WithDeadline` 设定截止时间
      • 五、传递上下文中的数据:`WithValue`
      • 六、Context 的应用场景
      • 七、完整示例:多任务协作控制
      • 八、小结

一、简介

在并发编程中,任务管理和资源控制是非常重要的,而 Golang 的 context 为我们提供了一种优雅的方式来传递取消信号超时控制Context 用于在多个 Goroutine 之间传递上下文信息,避免 Goroutine 无法按需停止而导致资源浪费。

本篇博客将详细介绍 context 包的用法,并通过实例讲解如何在超时、取消任务多 Goroutine 协作场景中使用它。


二、Context 的基本概念

Context 是一种携带取消信号、截止时间(超时)和元数据的上下文对象,主要用于父 Goroutine 与子 Goroutine 的协作。它通过层级化的结构来管理多个并发任务。

1. context 包常用函数
  • context.Background():创建根上下文,通常用于程序入口。
  • context.TODO():占位符上下文,表示未来会替换为实际上下文。
  • context.WithCancel(parent Context):创建带取消功能的子上下文。
  • context.WithTimeout(parent Context, timeout time.Duration):创建带超时功能的子上下文。
  • context.WithDeadline(parent Context, deadline time.Time):基于指定的截止时间创建上下文。
  • context.WithValue(parent Context, key, value interface{}):传递携带额外数据的上下文。

三、Context 的基本用法

1. WithCancel:取消任务的上下文

示例:使用 WithCancel 取消 Goroutine

package mainimport ("context""fmt""time"
)func worker(ctx context.Context, id int) {for {select {case <-ctx.Done(): // 接收取消信号fmt.Printf("Worker %d stopped\n", id)returndefault:fmt.Printf("Worker %d is working...\n", id)time.Sleep(time.Second)}}
}func main() {ctx, cancel := context.WithCancel(context.Background()) // 创建可取消的上下文for i := 1; i <= 3; i++ {go worker(ctx, i)}time.Sleep(3 * time.Second) // 模拟主 Goroutine 的其他工作fmt.Println("Cancelling all workers...")cancel() // 发送取消信号time.Sleep(1 * time.Second) // 等待所有 Goroutine 退出fmt.Println("All workers stopped.")
}

输出:

Worker 1 is working...
Worker 2 is working...
Worker 3 is working...
...
Cancelling all workers...
Worker 1 stopped
Worker 2 stopped
Worker 3 stopped
All workers stopped.

解析:

  • context.WithCancel 创建的上下文可以通过调用 cancel() 发送取消信号,从而优雅地停止所有子 Goroutine。

四、超时控制:WithTimeoutWithDeadline

1. 使用 WithTimeout 控制任务超时

示例:在 2 秒内完成任务,否则超时退出

package mainimport ("context""fmt""time"
)func worker(ctx context.Context) {select {case <-time.After(3 * time.Second): // 模拟长时间任务fmt.Println("Task completed")case <-ctx.Done(): // 接收超时信号fmt.Println("Task timed out")}
}func main() {ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) // 设置 2 秒超时defer cancel() // 确保资源释放go worker(ctx)time.Sleep(4 * time.Second) // 等待任务完成或超时
}

输出:

Task timed out

解析:

  • 通过 context.WithTimeout 创建的上下文,2 秒内未完成任务时自动发送取消信号。
  • 超时上下文可避免 Goroutine 无限期运行,帮助更好地管理资源。
2. 使用 WithDeadline 设定截止时间

WithDeadlineWithTimeout 类似,只是使用具体的时间点来控制超时。


五、传递上下文中的数据:WithValue

有时,我们需要在多个 Goroutine 之间传递一些元数据。WithValue 允许我们将键值对存入上下文,并在子 Goroutine 中访问。

示例:传递用户信息

package mainimport ("context""fmt""time"
)func greetUser(ctx context.Context) {if user, ok := ctx.Value("user").(string); ok {fmt.Printf("Hello, %s!\n", user)} else {fmt.Println("No user found.")}
}func main() {ctx := context.WithValue(context.Background(), "user", "Alice") // 在上下文中存入用户信息go greetUser(ctx)time.Sleep(1 * time.Second) // 确保 Goroutine 执行完毕
}

输出:

Hello, Alice!

解析:

  • WithValue 允许我们为上下文设置键值对,便于在多 Goroutine 间传递数据。

注意:

  • 不建议用 WithValue 传递重要的控制信息,例如取消信号或超时。

六、Context 的应用场景

  1. API 请求的超时控制:确保 HTTP 请求不会无限期等待。
  2. 任务取消:当用户主动取消某个操作时,通知相关的 Goroutine 停止工作。
  3. 传递元数据:例如在服务链路中传递用户身份、请求 ID 等信息。

七、完整示例:多任务协作控制

示例:启动多个任务,随时可取消所有任务

package mainimport ("context""fmt""sync""time"
)func worker(ctx context.Context, id int, wg *sync.WaitGroup) {defer wg.Done()for {select {case <-ctx.Done():fmt.Printf("Worker %d stopped\n", id)returndefault:fmt.Printf("Worker %d is processing...\n", id)time.Sleep(500 * time.Millisecond)}}
}func main() {var wg sync.WaitGroupctx, cancel := context.WithCancel(context.Background()) // 创建上下文for i := 1; i <= 3; i++ {wg.Add(1)go worker(ctx, i, &wg)}time.Sleep(2 * time.Second)fmt.Println("Cancelling all workers...")cancel() // 取消所有任务wg.Wait() // 等待所有任务完成fmt.Println("All workers stopped.")
}

输出:

Worker 1 is processing...
Worker 2 is processing...
Worker 3 is processing...
...
Cancelling all workers...
Worker 1 stopped
Worker 2 stopped
Worker 3 stopped
All workers stopped.

八、小结

  1. Context 用于并发控制:在 Goroutine 中传递取消信号、超时信号或携带元数据。
  2. 超时控制与资源管理:使用 WithTimeoutWithCancel 及时终止任务,避免资源浪费。
  3. 多 Goroutine 协作:通过 Context 实现多个 Goroutine 之间的优雅通信。

http://www.yayakq.cn/news/306423/

相关文章:

  • 如何做汽车的创意视频网站河南省监理协会官方网站建设
  • 智慧团建网页版手机登录网站的内部优化
  • 青浦手机网站建设在建设工程信息网
  • 奇单网站建设表白网址在线制作平台
  • 面对撞库 网站应该怎么做淘宝网网页版登录入口
  • 做网站老板嫌弃太丑谁的锅沙河网站建设
  • 诸城网站建设多少钱桃城网站建设
  • 网站设计西安网站建设html5 网站开发实战
  • 旅游网站模板免费下载网站建设 域名 数据库
  • php网站开发目录wordpress 主题添加标签
  • 城市建设模拟游戏官方网站关于网的设计创意作品
  • 网站后台密码破解教程网站主色调有几种
  • 做网站设计的平台网站架构招聘
  • 青岛网上房地产网站联系深圳网站制作公司
  • 冬奥会建设官方网站做网页制作的价格
  • 北京app开发网站建设WordPress底部添加版权注明
  • 旅游网站设计策划书wordpress 取消响应式
  • 想要学做网站需要什么动漫设计属于什么大类
  • 怎样辨别网站简单的管理系统
  • 手机网站开发服务网页关键词排名优化
  • 做推送的网站有哪些wordpress做门户
  • 做网站时需要注意什么自己名字怎么设计logo
  • 高端网站建设 选择磐石网络爱你社区
  • 请问聊城网站建设网页制作的公司为什么瓯北没有
  • 金山专业网站建设保定公司网站建设
  • 网站网站建设设计公司网站域名正在维护中
  • 徐州专业做网站顺企网宁波网站建设
  • 温州做网站整站优化知识营销案例有哪些
  • 深圳网站建设服务找哪家昆明室内设计公司排名
  • 建设网站哪个便宜菜鸟如何做网站