为何会收到不明来源的额外元素?
时间:2024-03-21
浏览:428
作者:佚名
遇到一个特殊问题,在两个协议 a 和 b 中出现恐慌,即使协议 a 单独运行时正常。当调用协议 b 时,在协议 a 中会收到额外的 *big.int,导致接口转换错误。尽管协议 a 已在步骤 2 中接收各方的 *big.int,但在步骤 4 中却意外收到了 *big.int。经过调查,发现该错误源于协议 b 重用了 chan 接口{},导致竞争条件,从而在步骤 4 中发送了错误的数据类型。
我遇到了一个特殊的问题,不幸的是我无法在最小的工作示例中重现该问题。我会尽力解释它,希望你至少能给我一些提示。
我有两个协议:a 和 b。对于每个协议,都有一个中心方 p1 和三个外部方,我们将其称为 pn。每一方都作为一个单独的 goroutine 实现。
协议a如下:
- 各方分别执行计算,并将
*big.int类型的结果发送至 p1。 - p1 接收所有结果并将它们放入一个切片中,然后将其发送回各方pn。
- 所有各方都会收到切片并根据它执行新的计算,并将
*decryptionshare类型的结果发送到 p1。 - p1接收所有数据并计算结果。
- 各方输出结果
*big.int。
为了解决这个问题,我有三个通道,一个用于发送数据p1 -> pn,一个用于pn -> p1 和一个将最终结果输出回主线程(即所有 pn 从相同通道读取和写入)。 pn 的结果 1. 和 3. 具有不同的类型,因此通道类型为 interface{}。
协议b首先启动协议a,然后进行进一步的计算,这是不相关的。
这是我的问题:
协议a本身就可以工作,从未出现过问题。 但是,当我调用 b 约 10% 的运行时,它会在 a 中出现恐慌,即使唯一不同的是 b 传递输入参数到a。
显示的错误是
panic: interface conversion: interface {} is *big.int, not *decryptionshare
这意味着p1在第4步时收到了*big.int,尽管它已经在第2步中收到了各方*big.int。
我尝试使用 time.sleep 和 select 在步骤 2 上停留更长的时间,但我从未在该步骤中获得额外的 *big.int,它只是偶尔出现在步骤 4 中。
如果我不是 chan 接口{} 使用两个单独的通道 chan *big.int 和 chan *decryptionshare 协议 b 正确终止,这也意味着从通道中正确读取所有内容(即没有线程)被阻止)。我希望避免这种情况,因为我已经有很多频道在使用。
有人知道为什么会发生这种恐慌吗?
编辑:
这是一个最小的工作示例,但不会产生错误。希望它能够获得一些见解。 *decryptionshare 替换为 int。
package tpsi
import (
"math/big"
"fmt"
"crypto/rand"
"testing"
)
type DecryptionShare struct {
index int
p *big.Int
}
func TestErs(t *testing.T) {
message_channel1 := make(chan interface{})
message_channel2 := make(chan []*big.Int)
return_channel := make(chan *big.Int)
n := 4
go CentralParty(n, message_channel2, message_channel1, return_channel)
for i := 1; i < n; i += 1 {
go OtherParty(message_channel1, message_channel2, return_channel)
}
for i := 0; i < n; i += 1 {
fmt.Println(<-return_channel)
}
t.Error("for display")
}
func CentralParty(n int, sender_channel chan<- []*big.Int, reciever_channel <-chan interface{}, return_channel chan<- *big.Int) {
p, err := rand.Prime(rand.Reader, 256)
if err != nil {panic(err)}
all_p := make([]*big.Int, n)
all_p[0] = p
for i := 1; i < n; i += 1 {
all_p[i] = (<-reciever_channel).(*big.Int)
}
for i := 1; i < n; i += 1 {
sender_channel <- all_p
}
shares := make([]*DecryptionShare, 4)
for i := 1; i < n; i += 1 {
shares[i] = (<-reciever_channel).(*DecryptionShare)
}
return_channel <- shares[1].p
}
func OtherParty(sender_channel chan<- interface{}, reciever_channel <-chan []*big.Int, return_channel chan<- *big.Int) {
p, err := rand.Prime(rand.Reader, 256)
if err != nil {panic(err)}
sender_channel <- p
all_p := <-reciever_channel
var ds DecryptionShare
ds.p = p
ds.index = all_p[0].BitLen()
sender_channel <- &ds
return_channel <- p
}解决方案
在几位评论者的共同压力下,我强迫自己获得了 MWE。正如 @oakad 所建议的,我在这样做时发现了该错误。
该错误(不出所料)来自协议 B,该协议重用了 chan 接口{},再次发送第一个数据类型 *big.Int,从而引入竞争条件。
我完全忽略了考虑跨协议的竞争条件。
感谢您的评论!
到这里,我们也就讲完了《为何会收到不明来源的额外元素?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
