gpt4 book ai didi

go - 我的 golang 代码有什么问题?

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:14 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why my golang lock free queue always stuck there?

这是我的全部源代码:

package main

import (
"sync/atomic"
"unsafe"
"sync"
"fmt"
"time"
"runtime"
)

const (
MAX_DATA_SIZE = 100
)

// lock free queue
type Queue struct {
head unsafe.Pointer
tail unsafe.Pointer
}
// one node in queue
type Node struct {
val interface{}
next unsafe.Pointer
}
// constructor
func New() (q *Queue) {
queue := new(Queue)
queue.head = unsafe.Pointer(new(Node))
queue.tail = queue.head
return queue
}
// queue functions
func (self *Queue) enQueue(val interface{}) {
newValue := unsafe.Pointer(&Node{val: val, next: nil})
var tail,next unsafe.Pointer
for {
tail = self.tail
next = ((*Node)(tail)).next
if atomic.CompareAndSwapPointer(&next, nil, newValue) {
atomic.CompareAndSwapPointer(&self.tail, tail, newValue)
break
}else{
for next != nil {
tail = next
}
}
}
}

func (self *Queue) deQueue() (val interface{}, success bool){
var head,next unsafe.Pointer
for {
head = self.head
next = ((*Node)(head)).next
if next == nil {
return nil, false
}else {
if atomic.CompareAndSwapPointer(&(self.head), head, next) {
val = ((*Node)(next)).val
return val, true
}
}
}
return nil, false
}

func main() {
//runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.GOMAXPROCS(-1))
var wg sync.WaitGroup
wg.Add(20)
queue := New()
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for j := 0; j < MAX_DATA_SIZE; j++ {
t := time.Now()
fmt.Println("enqueue111")
fmt.Println("enq = ", t)
fmt.Println("enqueue222")
queue.enQueue(t)
}
}()
}

for i := 0; i < 10; i++ {
go func() {
ok := false
var val interface{}
defer wg.Done()
for j := 0; j < MAX_DATA_SIZE; j++ {
val,ok = queue.deQueue()
for !ok {
val,ok = queue.deQueue()
}
fmt.Println("deq = ",val)
}
}()
}

wg.Wait()
}

代码卡在fmt.Println("enq = ", t) 但我不知道为什么,它太奇怪了。

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