我的golang代码有什么问题

我的golang代码有什么问题

本文介绍了我的golang代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的完整源代码:

Here's my whole source code :

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()
}

推荐答案

deQueue在无效情况下无限循环,阻塞CPU。在执行CPU工作时,Goroutine不会产出。 GOMAXPROCS需要大于等于2才能获得CPU并行性。

deQueue is looping infinitely on the fail case, which is blocking the CPU. Goroutines don't yield while doing CPU work. GOMAXPROCS needs to be >= 2 to get CPU parallelism.

仅用于踢球,这是一个使用高阶通道的线程安全非阻塞队列实现:

just for kicks, here's a threadsafe, nonblocking queue implementation using higher-order channels: https://gist.github.com/3668150

这篇关于我的golang代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:50