What is an example of a hard programming challenge that has an elegant solution in Go but not others languages?
<p>I am thinking a problem that is easy to solve with Go but not others will need to make use of channel and go routines. But I can't seem to think of one. </p> <hr/>**评论:**<br/><br/>cdoxsey: <pre><p>TCP Proxy</p> <pre><code>func run() error { li, err := net.Listen("tcp...阅读全文
Searching for internship in companies use Go.
<p>Hello everyone, I'm searching for an winter internship and I prefer doing it with Golang. So does anyone know startups/companies use Go and maybe accepting interns ? Thanks.</p> <hr/>**评论:**<br/><br/>condanky: <pre><p>Depends on where you are located. <a href="https://www.golangprojects.co...阅读全文
How to reliably detect if an UDPConn is closed?
<p>Hi gophers!</p> <p>I'm trying to detect, reliably, if an UDPConn is closed, when I receive an error from <code>WriteTo()</code> function. The error.Error() has the suffix <code>use of closed network connection</code> so I can check for that suffix in the error message, but it doesn't fee...阅读全文
MixPHP V2.1 生态: Swoole 协程 Redis 订阅器
在 OpenMix 全家桶 中有一个 Mix Redis Subscribe 的项目,这是一个不依赖 phpredis 扩展,直接解析 Redis 协议专用于订阅处理的一个库,任何 Swoole 框架都可使用,可广泛使用于 WebSocket 开发中,在 MixPHP 骨架中也默认包含了这个库。 为何开发 MixPHP V2.1 完成开发后,我试图开发一个基于订阅机制的 WebScoket 服务,该服务需要可动态切换订阅频道,但 phpredis 的订阅方法无法实现以下功能: $redis = new \Redis(); $res = $redis->pconnect('127.0.0.1', 6379, 0); $redis->subscribe(['test'], function ($...阅读全文
《Go in Action》第6章Concurrency
这篇是第6章,并发。 go中的concurrency是什么? A: Concurrency in Go is the ability for functions to run independent of each other. When a function is created as a goroutine, it’s treated as an independent unit of work that gets scheduled and then executed on an available logical processor. go语言中的Concurrency就是指函数能够独立于彼此运行的能力。当一个函数被创建成一个goroutine,其就被当成了一个独立的工作单元,并被调...阅读全文
Any examples of a clean way to renew a timeout timer?
<p>Hey there, I'm looking for a clean method to reset a timer being used <a href="https://blog.golang.org/go-concurrency-patterns-timing-out-and" rel="nofollow">similar to this example of a timeout with a select statement.</a></p> <p>My use case is worker goroutines pulling from an sqs queue an...阅读全文
golang面试基础系列-解锁deadlock(四)
在 go 中经常会使用 channel,进行并发执行子任务,提高执行效率。但一不小心就会踩到 deadlock 的坑,本文就来解析一下常见的死锁形式和解决方式。 1. 直接读取空 chan 产生死锁 package main import ( "fmt" ) func main() { ch := make(chan int, 3) <-ch } 输出结果: fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive]: main.main() /home/work/code/golang/src/interview/go/deadlock/test.go:9 +0x56 Process finis...阅读全文
How secure is this for communication between client and server?
<p>I will have a client and a server the client will have the public key while the server the private. The client sends some encrypted text to the server where its decrypted and handled... How secure is this? I am planning on using a 2048 Bit key pair.</p> <pre><code>package main import ( "crypto/rand" ...阅读全文
【Golang】singleflight 源码注释
在引入本地 cache 的场景下,缓存失效回源时会将请求打到后台数据库,在高并发时会带来性能和稳定性隐患。 singleflight 能够使多个并发请求所触发的回源操作里,只有第一个回源被执行,其余请求阻塞等待第一个被执行的那个回源操作完成后,直接取其结果,以此保证同一时刻只有一个回源操作在执行,以达到防止击穿的效果。 源码注释如下: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package singlefligh...阅读全文
13.Go语言标准库之time包
1.time包 time包提供了时间的系那是和测量用的函数。日历的计算采用的是公历。 1.1时间类型 time.Time类型表示时间。我们可以通过time.Now()函数获取当前的事件对象,然后获取时间对象的年月日时分秒等信息。 package main import ( "fmt" "time" ) func main() { now := time.Now() //获取当前时间 fmt.Printf("current time:%v\n", now) year := now.Year() //年 month := now.Month() //月 day := now.Day() //日 hour := now.Hour() //小时 minute := now.Minute() //分钟...阅读全文
Please explain this code (channels)
<p>I can't understand howcome only the loop part of total() function being run 3 times not the whole function. res := 0 runs only once while range part runs 3 times. My background is in Python and Java and the way total function is run not making sense at all. </p> <p><a href="http://pastebin.com/4fEvfGsU" rel=...阅读全文
说说不知道的Golang中参数传递
本文由云+社区发表 导言 几乎每一个C++开发人员,都被面试过有关于函数参数是值传递还是引用传递的问题,其实不止于C++,任何一个语言中,我们都需要关心函数在参数传递时的行为。在golang中存在着map、channel和slice这三种内建数据类型,它们极大的方便着我们的日常coding。然而,当这三种数据结构作为参数传递的时的行为是如何呢?本文将从这三个内建结构展开,来介绍golang中参数传递的一些细节问题。 背景 首先,我们直接的来看一个简短的示例,下面几段代码的输出是什么呢? //demo1 package main import "fmt" func test_string(s string){ fmt.Printf("inner: %v, %v\n",s, &s) s = "b...阅读全文
深度解密Go语言之channel
大家好!“深度解密 Go 语言”系列好久未见,我们今天讲 channel,预祝阅读愉快!在开始正文之前,我们先说些题外话。 上一篇关于 Go 语言的文章讲 Go 程序的整个编码、编译、运行、退出的全过程。文章发出后,反响强烈,在各大平台的阅读量都不错。例如博客园登上了 48 小时阅读排行榜,并且受到了编辑推荐,占据首页头条位置整整一天;在开发者头条首页精选的位置霸榜一周时间…… 熟悉码农桃花源的朋友们都知道,这里每篇文章都很长,要花很长时间才能读完。但长并不是目的,把每个问题都讲深、讲透才是最重要的。首先我自己得完全理解才行,所以写每篇文章时我都会看很多参考资料,看源码,请教大牛,自己还要去写样例代码跑结果……从创建文稿到真正完成写作需要很长时间。 做这些事情,无非是想力求我写出来的文字,都...阅读全文
Re: ESR's comparison of concurrency in Go and Rust
<p>Recently ESR posted a comparison of Rust's and Go's concurrency solutions on the NTPSec blog which was <a href="https://www.reddit.com/r/golang/comments/5os5zo/rust_vs_go/?ref=search_posts">shared here</a>. I wanted to respond to (all of it but right now only) this:</p> <blockquote> <p>...阅读全文
secretstream: a port of secret-handshake to go
<p><a href="https://scuttlebot.io/more/protocols/secret-handshake.html">secret-handshake</a> is the cypher-channel used by <a href="https://scuttlebot.io/">secure-scuttlebot</a> the peer-to-peer append-only log database.</p> <p>It uses NaCL primitives to exchange keys and build streams. Als...阅读全文
golang context
最初接触golang http源码的时候就发现有一个比较特别的package context,并且在后面学习etcd源码的时候发现几乎每一个回调相关的函数都会有一个ctx参数,顺便了解下它的实现原理以及设计思想。 context 的作用 context结合自己工作实践,我认为context主要有以下两个作用: 1.传递数据 2.递归的取消子任务 context包在golang源码的golang.org/x/net/context目录下,context主要用在结束若干个相互具有父子(主任务子任务)关系的goroutine,context内部本身就是以一种树形递归的形式去组织各个context节点,父节点的取消,会递归的把取消信号发送给它的子节点。 Context接口的定义如下: type ...阅读全文
why my code exits with a fatal error: all goroutines are sleep??
<p>Hi guys, I could found many codes than show the same error, but unfortunately all them are different to my code (in general they forgot use sync.WaitGroup and the main thread was exiting before run the goroutines)</p> <p>my code is</p> <p>package main</p> <p>import "fmt" import &#...阅读全文
What's your experience with Go on mobile (bind only)?
<p>I am writing a cross-platform app targeting both desktop and mobile (Android, iOS). I settled on either writing my business logic in C++ or Go, the UI is written separately for each platform.</p> <p>Are there any caveats to take into account when writing Go for mobile, if all I am using is the standard library and selected lib...阅读全文
Care to give a little help to a gopher in need?
<p>So, I have this package: <a href="https://github.com/nubunto/ports" rel="nofollow">https://github.com/nubunto/ports</a> Basically, a test that provides an API for a interface in Go to a external program. There's a test in there. That test is failing, with a deadlock. Any insights on the why?</p> &...阅读全文
[Question] - Do we always need to use go channels to take advantage of multiple cores?
<p>Forgive the silly question, but, I am coming from a node background because quite frankly I am really sick of spinning up multiple instances and handling shared data with Redis. I just want to run one instance of my game per server and I heard GoLang can do that. I also heard Go blows node out of water doing it. And I've seen the b...阅读全文
Go嵌套并发实现EDM,附坑点分析#1
看着身边优秀的小伙伴们早就开始写博客,自己深感落后,还好迟做总比不做好,勉励自己见贤思齐。趁着年前最后一个周末,阳光正好,写下第一篇博客,为2019年开个头,以期完成今年为自己立下的flags。 从PHPer转Gopher,很大一个原因就是业务对性能和并发的持续需求,另一个主要原因就是Go语言原生的并发特性,可以在提供同等高可用的能力下,使用更少的机器资源,节约可观的成本。因此本文就结合自己在学习Go并发的实战demo中,把遇到的一些坑点写下来,共享进步。 1. 在Go语言中实现并发控制,目前主要有三种方式: a) Channel - 分为无缓冲、有缓冲通道; b) WaitGroup - sync包提供的goroutine间的同步机制; c) Context - 在调用链不同gorouti...阅读全文
What is best practice API for returning an asynchronous result from a function?
<p>TLDR Problem: I want to design an API call that does something asynchronously and I'm unsure about the best practice way to do this.</p> <hr/> <p>Say the API I want to expose is a function TimeConsumingTask(), which eventually returns a TaskResult. My first inclination would be to write something like:</p&g...阅读全文
Go语言入门(七)goroutine和channel
goroutine和channel goroutine 多线程 func hello() { //fmt.Printf("Hello Goroutine!!\n") for i:=0;i<100;i++ { fmt.Printf("hello:%d\n",i) time.Sleep(time.Millisecond) } } func main() { go hello() //启动了一个独立的线程,使其与下面的代码交替执行,使之成为一个多线程 //fmt.Printf("main function\n") for i:=0;i<100;i++ { fmt.Printf("main:%d\n",i) time.Sleep(time.Millisecond) } time.Sleep(time...阅读全文
Golang中make和new的区别
new:func new(Type) *Type 接受一个参数,这个参数是一种类型,而不是一个值,分配好内存后, 返回一个指向该类型内存地址的指针,这个指针指向的内容的值为该类型的零值。 对于不同的数据类型,零值的意义是完全不一样的。 比如,对于bool类型,零值为false;int的零值为0;string的零值是空字符串 make:func make(t Type, size ...IntegerType) Type 同样用于内存分配,但和new不同,make用于channel,slice和map的分配, 而且返回的类型就是这三个类型本身,而不是它们的指针, 因为这三种类型本身就是引用类型,所以就没必要返回他们的指针了。 具体而言,有如下几种用法: (1)make(map[string]s...阅读全文
Advice about job queue solution for Go
<p>Hi</p> <p>I'm writing a service which listens on rest endpoints and starts jobs accordingly: think something like processing 1000 image files and generating thumbnails for each one. I'm gonna have a few tasks of different priorities and different parallel-isability. Can someone recommend a way to implement this...阅读全文
【协程初步讨论 2019-4-24】 简单扩展
grape 全部视频:https://segmentfault.com/a/11... 原视频地址:https://biglive.xueersi.com/L... GO协程有关知识(扩展) Go语言最大的特色就是从语言层面支持并发(Goroutine),Goroutine是Go中最基本的执行单元。事实上每一个Go程序至少有一个Goroutine:主Goroutine。当程序启动时,它会自动创建。 首先了解什么是协程,什么是线程 协程:又称微线程与子例程(或者称为函数)一样,协程(coroutine)也是一种程序组件。相对子例程而言,协程更为一般和灵活,但在实践中使用没有子例程那样广泛。和线程类似,共享堆,不共享栈,协程的切换一般由程序员在代码中显式控制。它避免了上下文切换的额外耗费,兼顾了...阅读全文
Question about Goroutines and spreading a load across multiple cores/threads.
<p>tl;dwtr (too long; don't want to read): Last paragraph has my question.</p> <p>I am currently trying to get better acquainted with Go by writing what amounts to a benchmarking suite. However, I am not running a single-core computer, and I am trying to find a way to keep my processor pegged at 100 (or as close to it as ...阅读全文
2019-06-26
本文介绍了fabric中的一个示例应用balance-transfer,fabric版本是1.4.1。本文基于上一章hyperledger基础培训-创建第一个fabric网络的基础上,如果还未了解,请先了解上一章节内容。 balance-transfer是什么 balance-transfer是Hyperledger fabric Node SDK的一个示例应用,主要使用了SDK中fabric-client 和 fabric-ca-client 模块中的API,实现了与Fabric网络交互的各种操作。 1. 预装环境 预装环境在上一章节hyperledger基础培训-创建第一个fabric网络已有详细介绍,可跳转至该文章查看。 Docker - v1.12或更高版本 Docker Compo...阅读全文
Golang之channel
前言 go中的一个精髓就是就是channel,那么你有没有想过,它究竟是怎么实现的呢?我之前就怀疑过,是不是就是通过一个数组保存了一下传入的数据,然后在接收方读一读就完事了,那么阻塞又是怎么实现的呢?close的时候需要注意些什么呢? 结构 首先我们来看一下channel的结构是怎么样的。 type hchan struct { qcount uint // total data in the queue dataqsiz uint // size of the circular queue buf unsafe.Pointer // points to an array of dataqsiz elements elemsize uint16 closed uint32 elemtype ...阅读全文
Golang new和 make的区别
Go提供了两种分配原语,即new和make。它们所做的事情是不一样的,所应用的类型也不同。new用来分配内存,但与其他语言中的同名函数不同,它不会初始化内存,只会讲内存置零;也就是说,new(T)会为类型为T的新项分配已置零的内存空间,并返回他的地址,也就是一个类型为*T的值。用Go的术语来说,它返回一个指针,改指针指向新分配的,类型为T的零值;make的目的不同于new,它只用于slice,map,channel的创建,并返回类型为T(非指针)的已初始化(非零值)的值;出现这种差异的原因在于,这三种类型本质上为引用类型,它们在使用前必须初始化;小结:new和make都在堆上分配内存,但是它们的行为不同,适用于不同的类型。new(T) 为每个新的类型T分配一片内存,初始化为 0 并且返回类型...阅读全文
29. Go 语言中的 select 用法
Hi,大家好,我是明哥。 在自己学习 Golang 的这段时间里,我写了详细的学习笔记放在我的个人微信公众号 《Go编程时光》,对于 Go 语言,我也算是个初学者,因此写的东西应该会比较适合刚接触的同学,如果你也是刚学习 Go 语言,不防关注一下,一起学习,一起成长。 我的在线博客:http://golang.iswbm.com我的 Github:github.com/iswbm/GolangCodingTime 前面写过两节关于 switch-case 的文章,分别是: 流程控制:switch-case Go 语言中的类型断言 今天要学习一个跟 switch-case 很像,但还有点个人特色 的 select-case,这一节本应该放在 学习 Go 协程:详解信道/通道 里一起讲的,但是当...阅读全文
int64 vs int | Adding in GoLang
<p>So I am sorry if this is the wrong subreddit to be posting this but I ran into an unusual error today that I wasn't able to come up with a solution for... I have a string being parsed to an int via strconv.ParseInt which returns an int64, but once I have the int64 I cannot seem to add other numbers to it. Is there something I am mi...阅读全文
golang rabbitmq的使用(三)
在第二篇中讲到了fanout类型的exchange,fanout类型exchange会将消息发送到所有和其连接的queue中,不会去区分和过滤。但现实中我们往往需要有过滤条件将不同的消息区分开来发到不同的queue。举个简单的例子,系统的log。我们需要将收到的log根据info,debug,warn,error发送到不同的queue,由不同的consumer来处理这些不同的log。为了实现这个功能我们可以 ExchangeDeclare是指定type为direct err = ch.ExchangeDeclare( "syslog_direct", //exchange name "direct", //exchange type true, //durable false, //auto...阅读全文
You've been sentenced to death (you totally did it), what are your last words?
<hr/>**评论:**<br/><br/>Lazerc0bra: <pre><p>"Pull the lever Kronk!"</p></pre>und88: <pre><p>WRONG LEEEEEVVVVVEEEEERRRR</p></pre>Aganiel: <pre><p>Why do we even HAVE that lever</p></pre>FarOutPlaces: <pre><p>I know. By all accounts it ...阅读全文
【每日笔记】【Go学习笔记】2019-01-10 codis proxy处理流程
张仕华 proxy启动 cmd/proxy/main.go文件 解析配置文件之后重点是proxy.New(config)函数 该函数中,首先会创建一个Proxy结构体,如下: type Proxy struct { mu sync.Mutex ... config *Config router *Router //Router中比较重要的是连接池和slots ... lproxy net.Listener //19000端口的Listener ladmin net.Listener //11080端口的Listener ... } 然后起两个协程,分别处理11080和19000端口的请求 go s.serveAdmin() go s.serveProxy() 我们重点看s.serveProx...阅读全文
go学习笔记-goroutine的好兄弟channel
上一篇介绍了atomic包以及互斥锁 mutex来解决并发竞争状态的问题。这一篇主要来介绍go中与goroutine经常搭档的好兄弟channel channel不仅可以可以来用消除竞争状态,还可以用于不同的goroutine中进行通信,发送与接受数据。chaanel的定义有两种,分为有缓存与无缓冲 创建channel chan1 := make(chan int) // 创建一个无缓冲的 整形 channel chan2 := make(chan int,2)// 创建一个有缓冲的 整形 channel 上面的代码片段,我们分别创建了一个无缓冲的channel与一个有缓冲的channel。channel的创建是使用make(chan type,[lenght])来创建,如果指定了第二个参数...阅读全文
How many idioms did I break.
<p><a href="https://github.com/project-empower/randomart-image" rel="nofollow">https://github.com/project-empower/randomart-image</a></p> <p>It's a first stab at anything Go. I'm from C++. Would like a kind hearted soul to tell me how horrible it is...constructively :p</p> <...阅读全文
Golang 源码导读 —— channel
01.chan 的数据结构:golang 中 chan 的源码在 src/runtime/chan.go 文件中,hchan 则为 chan 的结构体 hchan:12345678910111213141516171819202122type hchan struct { qcount uint // 当前缓存数据的总量 dataqsiz uint // 缓存数据的容量 buf unsafe.Pointer // 缓存数据,为一个循环数组,容量大小为 dataqsiz,当前大小为 qcount elemsize uint16 // 数据类型的大小,比如 int 为 4 closed uint32 // 标记是否关闭 elemtype *_type // 数据的类型 sendx uint //...阅读全文
What do you think Go could/should do better?
<p>Recently I was discussing Go with a few colleagues who are new to the language and they mentioned several things that they wished Go supported or handled differently. The specifics aren't important, but it got me thinking. What do <em>you</em> think Go could/should do better?</p> <p>Personally, I'd ...阅读全文
golang并发----基础
Channels 创建channel 使用内置的make函数,我们可以创建一个channel // ch has type 'chan int' ch := make(chan int) // unbuffered channel ch = make(chan int, 0) // unbuffered channel ch = make(chan int, 3) // buffered channel with capacity 3 引用类型&零值&比较 和map类似,channel也对应一个make创建的底层数据结构的引用.当我们复制一个channel或用于函数参数传递时,我们只是拷贝了一个channel引用,因此调用者和被调用者将引用同一个channel对象. 和其它的引用类型一样,c...阅读全文
聊聊golang的context
golang的context的主要用途在于在多个goroutine之间传递数据,管理多个goroutine的生命周期。实际的应用场景有比如,在http服务中,每个请求就对应一个goroutine,而请求之中可能又会调用别的api,而产生更多的goroutine,用context来管理这些goroutine就能比较方便在这些goroutine中传递数据和管理。 主要方法 func Background() Context Background() 返回一个空的context,这是一个根节点。 func TODO() Context TODO()返回的也是一个空的context,它跟Background的区别在于目的,当你使用一个todo的context时,代码维护者便知道当时的设计意图是待定的...阅读全文
golang基础语法-2
该篇接着上一篇延续,是一个完整的系列 第 5 章 方法 5.1 方法定义 方法总是绑定对象实例,并隐式将实例作为第一实参 (receiver)。 只能为当前包内命名类型定义方法。 参数 receiver 可任意命名。如方法中未曾使用,可省略参数名。 参数 receiver 类型可以是 T 或 *T。基类型 T 不能是接口或指针。 不支持方法重载,receiver 只是参数签名的组成部分。 可用实例 value 或 pointer 调用全部方法,编译器自动转换。 没有构造和析构方法,通常用简单工厂模式返回对象实例。 type Queue struct { elements []interface{} } func NewQueue() *Queue { // 创建对象实例。 return &Q...阅读全文
GO译文之并发模型一 Pipeline和Cancellation
作者:Sameer Ajmani原文:https://blog.golang.org/pipelines介绍Go并发模型使构建能高效利用IO和多核CPU的实时流式数据的pipeline非常方便。这篇文章将对此进行介绍,同时会着重强调一些在实践中的易犯错误以及对应的解决方法。什么是Pipeline在GO中,pipeline无明确定义;它是语言提供的一种并发编程方式,由连接各个chanel而形成的一系列阶段组成。在其各个阶段,可能分别运行着很多的goroutine。这些goroutine从输入channel接收数据对数据作相应处理,例如在此基础上产生新数据再通过输出channel把数据发送出去除了开始和结束,每个阶段都会包含任意多个输入和输出channel。开始阶段只有输出channel,结束阶...阅读全文
Can you guarantee data consistency in one write to many read channel in golang?
<p>If I have 2 5 goroutine for read, and 1 goroutine for write, is there a way to make sure that every goroutine gets the entire write data?</p> <p>For example. </p> <p>In the following code whenever I write to main thread, one and only one goroutine gets the value.</p> <pre><code>package main imp...阅读全文
Go语言 Channel
Channel是Go中的一个核心类型,你可以把它看成一个管道,通过它并发核心单元就可以发送或者接收数据进行通讯(communication)。 它的操作符是箭头 <- 。 ch <- v // 发送值v到Channel ch中 v := <-ch // 从Channel ch中接收数据,并将数据赋值给v (箭头的指向就是数据的流向) 就像 map 和 slice 数据类型一样, channel必须先创建再使用: ch := make(chan int) Channel类型 Channel类型的定义格式如下: ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType . 它包括三种类型的定义。可选的<-代表channel的...阅读全文
golang-nsq系列(一)--初识
nsq 最初是由 bitly 公司开源出来的一款简单易用的分布式消息中间件,它可用于大规模系统中的实时消息服务,并且每天能够处理数亿级别的消息。 nsq 它具有以下特性: 分布式。它提供了分布式的、去中心化且没有单点故障的拓扑结构,稳定的消息传输发布保障,能够具有高容错和高可用特性。 易于扩展。它支持水平扩展,没有中心化的消息代理(Broker),内置的发现服务让集群中增加节点非常容易。 运维方便。它非常容易配置和部署,灵活性高。 高度集成。现在已经有官方的Golang、Python和JavaScript客户端,社区也有了其他各个语言的客户端库方便接入,自定义客户端也非常容易。 1. 首先到官方文档看用法: https://nsq.io/overview/quick_start.html q...阅读全文