"Go\u5143\u8bed\u8ba1\u6570\u5668\u5b9e\u73b0\u793a\u4f8b\u2014\u2014\u7ebf\u7a0b\u5b89\u5168\u8ba1\u6570\u5668"\n\n"\u4e0b\u9762\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u53bb\u8bed\u8bed\u8ba1\u6570\u5668\u7684\u5b9e\u73b0\u793a\u4f8b\uff1a"\n\n"go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype Counter struct {\n\tvalue int\n\tmutex sync.Mutex\n}\n\nfunc (c *Counter) Increment() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.value++\n}\n\nfunc (c *Counter) Decrement() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.value--\n}\n\nfunc (c *Counter) Value() int {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\treturn c.value\n}\n\nfunc main() {\n\tcounter := Counter{}\n\n\tcounter.Increment()\n\tfmt.Println(counter.Value()) // \u51fa\u51fb: 1\n\n\tcounter.Decrement()\n\tfmt.Println(counter.Value()) // \u51fa\u51fb: 0\n}\n"\n\n"\u5728\u8fd9\u4e2a\u793a\u4f8b\u4e2d\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a`Counter\u7ed3\u6784\u4f53\uff0c\u5b83\u5305\u542b\u4e00\u4e2a\value\u57df\u548c\u4e00\u4e2a\u76f8\u4e92\u9501\mutex\u3002\Increment\u65b9\u6cd5\u548c\Decrement\u65b9\u6cd5\u5206\u522b\u5bf9\value\u8fdb\u884c\u52a0\u4e00\u548c\u51cf\u4e00\u64cd\u4f5c\uff0c\u5e76\u4e14\u5728\u6267\u884c\u64cd\u4f5c\u524d\u5148\u83b7\u53d6\u76f8\u4e92\u9501\uff0c\u64cd\u4f5c\u5b8c\u6210\u540e\u963b\u65ad\u76f8\u4e92\u9501\u3002\Value\u65b9\u6cd5\u7528\u4e8e\u8fd4\u56de\u73b0\u5728\u8ba1\u6570\u5668\u7684\u503c\u3002\n\n\u5728\main\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a\Counter\u5f00\u59cb\u4f8b\u4f8b\counter\uff0c\u5e76\u8fdb\u884c\u4e86\u589e\u52a0\u548c\u51cf\u5c11\u64cd\u4f5c\uff0c\u7136\u540e\u6253\u5370\u8ba1\u6570\u5668\u7684\u503c\u3002\u6700\u7ec8\u51fa\u51fb\u4e3a\1\u548c\0`\u3002\

Go语言计数器实现示例 - 线程安全计数器

原文地址: https://www.cveoy.top/t/topic/qu6q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录