gpt4 book ai didi

go - channel 关闭后如何关闭 goroutines

转载 作者:行者123 更新时间:2023-12-03 10:08:01 25 4
gpt4 key购买 nike

<分区>

我正在尝试编写一个程序来同时挖掘一 block 比特币。我已经设置好它,以便每个 goroutine 都有一个初始的起始随机数,每个随机数都是 4 的一小部分,即。 2**64 - 1(uint64 类型的最大数量)/1 或 2 或 3 或 4。

这些矿工中只有一个会遇到正确的随机数,当这种情况发生时,我希望它通过一个 channel 将其传递给矿工经理,当这种情况发生时,我希望其他 3 名矿工停止他们正在做的事情.

唯一的问题是我不知道如何销毁正在运行的 goroutine,或者是否有办法完成我的要求。

func miner(blockNumber int, transactions string, previousHash string, zeroPrefix string, startNonce uint64, nonceChan chan uint64, hashChan chan string) {
var text string
var newHash string

for {
text = strconv.Itoa(blockNumber) + transactions + previousHash + strconv.FormatUint(startNonce, 10)
newHash = encrypt(text)

if startswith(newHash, zeroPrefix) {
nonceChan <- startNonce
hashChan <- newHash

close(nonceChan)
close(hashChan)
break
} else {
startNonce++
}
}
}

func mine(blockNumber int, transactions string, previousHash string, zeroPrefix int) Block {
var prefixString string
var newHash string
var nonce uint64
var startNonce uint64

nonceChan := make(chan uint64)
hashChan := make(chan string)

for i := 0; i < zeroPrefix; i++ {
prefixString += "0"
}

start := time.Now()

for i := 0; i < 4; i++{
// This line is for deciding at what nonce value a miner should start at.
startNonce = uint64((float64(i) / 4) * math.Pow(2, 64))

go func() {
fmt.Println("Started miner with start nonce of", startNonce)
miner(blockNumber, transactions, previousHash, prefixString, startNonce, nonceChan, hashChan)
}()
}

nonce = <- nonceChan
newHash = <- hashChan

// Here is where I would like to destroy the other three miners

block := Block{
blockNumber,
transactions,
previousHash,
newHash,
nonce,
zeroPrefix,
time.Since(start),
}

return block
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com