golang编程题

1、开启100个协程,顺序打印1-1000,并保证协程号为1的,打印尾数也是1

Go 复制代码
package main

import "fmt"

const (
	routineNum = 100
	numMax     = 1000
)

func main() {
	s := make(chan struct{})
	channels := make(map[int]chan int, 100)
	for i := 1; i <= routineNum; i++ {
		channels[i] = make(chan int)
	}
	for i := 1; i <= routineNum; i++ {
		go func(idx int) {
			for {
				num := <-channels[idx]
				fmt.Printf("chan id:[%d],num:[%d]\n", idx, num)
				s <- struct{}{}
			}

		}(i)
	}

	for j := 1; j <= numMax; j++ {
		idx := j % routineNum //0~99
		if idx == 0 {
			idx = routineNum
		}
		channels[idx] <- j
		<-s
	}
	return
}

2、3个goroutinue交替打印abc10次

Go 复制代码
package main

import (
	"fmt"
	"sync"
)

func main() {
	chan1 := make(chan struct{})
	chan2 := make(chan struct{})
	chan3 := make(chan struct{})
	var wg sync.WaitGroup
	wg.Add(3)

	go func() {
		defer wg.Done()
		for i := 0; i < 10; i++ {
			<-chan1
			fmt.Println("a")
			chan2 <- struct{}{}
		}
		<-chan1
	}()
	go func() {
		defer wg.Done()

		for i := 0; i < 10; i++ {
			<-chan2
			fmt.Println("b")
			chan3 <- struct{}{}
		}

	}()
	go func() {
		defer wg.Done()

		for i := 0; i < 10; i++ {
			<-chan3
			fmt.Println("c")
			chan1 <- struct{}{}
		}
	}()
	chan1 <- struct{}{}
	wg.Wait()

	close(chan1)
	close(chan2)
	close(chan3)
}

3、用不超过10个goroutinue打印不重复的打印slice中100个元素

4、用2个协程交替打印奇偶数

相关推荐
Bony-17 小时前
Golang 常用工具
开发语言·后端·golang
csbysj202017 小时前
Go 语言变量作用域
开发语言
牛奔17 小时前
GVM:Go 版本管理器安装与使用指南
开发语言·后端·golang
颜酱17 小时前
用填充表格法-继续吃透完全背包及其变形
前端·后端·算法
百***787517 小时前
2026 优化版 GPT-5.2 国内稳定调用指南:API 中转实操与成本优化
开发语言·人工智能·python
夏秃然17 小时前
打破预测与决策的孤岛:如何构建“能源垂类大模型”?
算法·ai·大模型
氷泠17 小时前
课程表系列(LeetCode 207 & 210 & 630 & 1462)
算法·leetcode·拓扑排序·反悔贪心·三色标记法
腥臭腐朽的日子熠熠生辉17 小时前
nest js docker 化全流程
开发语言·javascript·docker
奔跑的web.17 小时前
Vue 事件系统核心:createInvoker 函数深度解析
开发语言·前端·javascript·vue.js