channel怎么实现线程安全

题目来源:腾讯

答案:

channel结构如下

  1. type hchan struct {
  2. qcount uint // total data in the queue
  3. dataqsiz uint // size of the circular queue
  4. buf unsafe.Pointer // points to an array of dataqsiz elements
  5. elemsize uint16
  6. closed uint32
  7. elemtype *_type // element type
  8. sendx uint // send index
  9. recvx uint // receive index
  10. recvq waitq // list of recv waiters
  11. sendq waitq // list of send waiters
  12. // lock protects all fields in hchan, as well as several
  13. // fields in sudogs blocked on this channel.
  14. //
  15. // Do not change another G's status while holding this lock
  16. // (in particular, do not ready a G), as this can deadlock
  17. // with stack shrinking.
  18. lock mutex
  19. }

在定义时结构中包含一个读写锁
当想往chan中发送数据或者是接收数据时都会先给chan上锁
所以channel是线程安全的