const{createApp}=Vue const{createVuetify,useGoTo,useDisplay}=Vuetify var data={alert:{show:false,color:'success',text:'',timeout:0,},theme:{dark:false,},nav:{showDrawer:false,showTOC:true,tocPanel:0,tab:'account',post:{discussionId:6401,currentPage:1,targetPage:1,total:77,anchor:0,goToOptions:{container:null,duration:0,easing:'easeInOutCubic',offset:-100,},worker:null,task:[],active:[],apiLock:[],originLike:new Map([]),},related:{block:1,}},search:{width:80,text:null,loading:false,},tags:[{id:27,url:'/t/0e2e58346a045c7567770b2b3120',name:'Go',color:'#FFA726',icon:'mdi-language-go',},{id:26,url:'/t/317a6a296a045c7566775e0c475c',name:'C|CPP',color:'#FFA726',icon:'mdi-language-cpp',},],posts:[{id:76761,num:0,uid:713,content:'我不知道他的回答和我的回答哪个是有依据的,麻烦有大佬知道的,指正我一下,仅是探讨技术对错问题,谢谢。\u003Cbr\u003E\u003Cbr\u003E他一上来问我 go 的协程能否做到线程不能做到的事,而且至少重复问了我 3 次。我回:总的来说是可以加快程序的运行效率。他就讲出了他的理论和依据,既然 go 协程是要由线程去接管运行的,资源也是从线程分来的,那么何谈加快运行效率,你原本线程要做的事还是没变,而且还多了管理协程的开销。后来他又提了一些问题试图来让我相信他这个理论和依据,不知道其中某个问题的时候,我回的是:不耗费资源的操作时,协程要更快,在耗费资源较多时,还是线程更快。然后他还是在反复和我纠结这个问题。在我看来 go 的协程实现是分割原本线程的资源,做到更轻量化和更灵活的资源调度。调用完资源空闲了就可以及时 gc ,就可以用更少的资源去做更多的事。到最后,他才说,我的大前提是,要做的事是非常耗费资源的操作,就感觉很搞不懂。\u003Cbr\u003E\u003Cbr\u003E虽然我面试问题回答的很差,但是我依旧想知道这个问题,不知道有没有大佬来和我指正一下,\u003Cbr\u003E另外他还有第二个问题,既然协程这套理论这么牛逼,那么 c++ 为什么没有呢?(在我印象里 c++只有线程)',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:08:08',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76762,num:1,uid:701,content:'C++有协程啊,谁说没有的。。。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:24:56',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76763,num:2,uid:5864,content:'线程有上下文切换开销,协程没有(或者更小?)\u003Cbr\u003E线程占用内存大,协程占用内存更小,可以使用更多协程\u003Cbr\u003E\u003Cbr\u003E协程更多是为了异步/减少阻塞吧(不知道对不对哈)\u003Cbr\u003E为了减少阻塞,从 callback function -\u0026gt; async/await -\u0026gt; 协程\u003Cbr\u003E当遇到阻塞的时候,协程可以由协程调度器调度到其他协程,并且上下文切换的开销小。\u003Cbr\u003E如果换作线程,阻塞就浪费 cpu 了。\u003Cbr\u003E\u003Cbr\u003Ec++有协程了',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:29:54',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76764,num:3,uid:713,content:'哦?是有的吗?我不是 c++开发者,仅有的一点对 c++的认知可以理解成是跑个 hello world 的级别。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:30:35',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[27,],mentionUsers:[],likeUsers:[],},{id:76765,num:4,uid:2611,content:'\u0026gt; 在我看来 go 的协程实现是分割原本线程的资源,做到更轻量化和更灵活的资源调度\u003Cbr\u003E\u003Cbr\u003E没什么问题。更具体地说,很重要的一个原因是 userspace thread 完全省略了操作系统调度线程和内核态切换的开销。\u003Cbr\u003E\u003Cbr\u003E有一个类似的例子:为什么 C 语言里用 malloc() 分配内存,而不是直接调操作系统提供的 sbrk()?你让面试官想去吧。\u003Cbr\u003E\u003Cbr\u003E\u0026gt; 他还有第二个问题,既然协程这套理论这么牛逼,那么 c++ 为什么没有呢\u003Cbr\u003E\u003Cbr\u003E没更新过知识的愚昧认知。当今几乎所有现代语言里都有「协程」,只是具体含义和实现不同。我随便抓一把:Python 、JS/TS 、C++、Rust 、C#、J**a/Kotlin 、Lua 、Dart…',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:35:09',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76766,num:5,uid:11135,content:'假设你有一件事的情况下,协程的管理消耗时间远远大于执行时间,线程能比协程更快。但是你有很多件事的情况下,协程能省下很多上下文切换的开销,这部分远远大于协程的管理时间',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:36:44',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76767,num:6,uid:2497,content:'goroutinue 的上下文切换是比线程要轻量的,还有一个 goroutinue 初始化只需要才 2K 的内存,一个线程就要 8M ,随便并发一下都比线程的并发多很多',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:40:48',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76768,num:7,uid:849,content:'这人技术和处事都有问题,要是入职后是你直接上级或者同组的话,这个岗可以直接 PASS',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:47:13',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76769,num:8,uid:433,content:'一个协程不会比一个线程更快,但是一万个协程很可能会比一万个线程更快。因为线程本身就是一种资源。你们讨论的“消耗资源”太含糊了。争执前先定义清楚。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:47:45',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76770,num:9,uid:2611,content:'还有个老生常谈的称呼问题:\u003Cbr\u003E\u003Cbr\u003E协程 \u003D 有栈协程/虚拟线程/用户态线程。这是在说 Go 的 goroutinue 、J**a 的 Virtual Thread ;\u003Cbr\u003E\u003Cbr\u003E协程 \u003D 无栈协程/暂停之后能恢复的函数。这是在说 Python/Dart 的 Iterator 、Lua/C++20 的 Coroutines 、Rust 的 Future 状态机;\u003Cbr\u003E\u003Cbr\u003E协程 \u003D 可以指包装了一层 Dispatcher 的普通线程。这是在说 Kotlin 的 Coroutine + NewThreadDispatcher 。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:49:54',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[69,],mentionUsers:[],likeUsers:[],},{id:76771,num:10,uid:2910,content:'协程不是为了提高任何效率, 而是为了将异步编程简化成同步化, 1:N 有栈协程好几十年了, unix 和 windows 都有专门的 api, 不是什么新概念, 无栈协程是最近些年编译器进步兴起的',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:54:17',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76772,num:11,uid:713,content:'别人直接就把我 pass 了,他是一面,他觉得我回答的技术不太行。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:55:57',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76773,num:12,uid:13105,content:'\u0026gt; 那么何谈加快运行效率,你原本线程要做的事还是没变,而且还多了管理协程的开销\u003Cbr\u003E\u0026gt; go 的协程比系统的线程更慢\u003Cbr\u003E\u003Cbr\u003E老哥你是真分不清这两种表述吗…\u003Cbr\u003E\u003Cbr\u003E一个 CPU 密集的任务,机器不切换协程要跑 100 秒,管理协程花 1 秒,因此 101 \u0026gt; 100 协程更慢',ipRegion:'',updatedByUid:0,createdAt:'2025-03-21 23:59:22',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76774,num:13,uid:10904,content:'要搞清楚一个事,每一个问题,都是有其前提条件的。比如,面试官说线程比协程快,如果前提条件是并发数很低的情况(并发数比 CPU 核心数少),那么是对的。你认同的观点,同样也是有前提条件的。讨论一个问题前,要先划好场景,不然就是没完没了,毫无意义的扯皮。这家公司 pass 吧',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:00:03',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76775,num:14,uid:140,content:'C++的协程都已经出了好几年了\u003Cbr\u003E\u003Cbr\u003E我上星期才发了个帖子,用协程写 Demo 程序: /t/1117106',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:15:05',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76776,num:15,uid:58,content:'协程运行在线程内,怎么可能比线程更快?越是 CPU 密集型场景,协程越无用。线程跟 CPU 核心 1:1 绑定,设定好亲和性,才是最快的,多 CPU 时还要考虑 NUMA 尽量访问本地内存。\u003Cbr\u003E\u003Cbr\u003E协程搞到冒烟,也不可能比手搓的多线程实现更快,只不过多线程实现复杂度较高。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:39:21',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76777,num:16,uid:2745,content:'协程就是,一个线程里调度运行的函数。简单讲,当去做 io 读取操作,其实很多时候是内核在读取,用户态这时候没必要等着内核读取完,把这段时间给其他函数运行,等内核读取完后继续运行。\u003Cbr\u003E最常见场景,爬虫,每个请求中间大量是等待 io 读取网络时间,这时候用协程就好。 还有一个 ui 常见例子,点击读取 button ,去读一个大文件并显示当 list 里,以前为了不卡死 ui 要不异步去读,要开线程,都会回调满天飞。协程就好,ui 线程读取大文件,等待过程还继续处理 ui 事件,然后读取完,继续显示列表,甚至代码逻辑就在一起。\u003Cbr\u003E\u003Cbr\u003E线程是要有一套自己资源,开一个线程是废资源,其实现在配置无所谓,只不过多线程代码很多问题。但是如果代码都非 io 操作那就只能多开线程,这时候协程就没用了。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:41:35',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76778,num:17,uid:2853,content:'1 、goroutine 初始栈 2KB (会动态增长的,并不是说一定省内存了),而操作系统线程的栈通常 1MB\u003Cbr\u003E2 、Go 运行时内置调度器,相比线程由操作系统调度,goroutines 的上下文切换成本更低,避免内核态的开销。\u003Cbr\u003E3 、配合通道减少了竞争的问题,使用简单\u003Cbr\u003E缺点也有:\u003Cbr\u003E1 、没法控制怎么分配到 cpu 核上,开几个协程可能都挂一个线程上,,利用不了多核资源\u003Cbr\u003E2 、GUI 生态多是线程绑定,go 对这块的兼容很不好,没什么生态\u003Cbr\u003E3 、协程一旦执行阻塞系统调用,会把整个线程阻塞,导致该线程无法执行其他 goroutines ,降低并发效率\u003Cbr\u003E4 、协程不适合 CPU 密集型任务,因为没什么 io ,上下文切换反而增加了开销,,调度器也有损耗,不如用多线程直接绑定到核心上',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:51:03',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76779,num:18,uid:13637,content:'“耗费资源”这个概念在你们交谈里面变得很模糊,欠缺定义。\u003Cbr\u003E\u003Cbr\u003E楼主经验少点,工作几年了哦?可以刷些 Go 实现、Linux 调度的文章,了解下进程这块相关的知识。\u003Cbr\u003E面试官应该到最后解释一下的。\u003Cbr\u003E\u003Cbr\u003E\u003Cbr\u003EGo 的协程就是用户(态)自己管理的代码片段嘛,那资源的分配上相比 OS 提供的线程,肯定是能够自己 DIY 啦\u003Cbr\u003E至于 CPP ,那 CPP 人家是写 OS 的语言,我拿 CPP 写个 Linux 再写个 Golang 编译器,你说我 CPP 有没有协程?\u003Cbr\u003E\u003Cbr\u003Ehttps://dr**en.co/golang/docs/part3-runtime/ch06-concurrency/golang-goroutine/\u003Cbr\u003Ehttps://samwho.dev/memory-allocation/\u003Cbr\u003E\u003Cbr\u003Ehttps://www.luozhiyun.com/archives/518\u003Cbr\u003Ehttps://dr**en.co/golang/docs/part2-foundation/ch04-basic/golang-function-call/',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 00:55:40',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:76780,num:19,uid:570,content:'你 CPU 跑满那肯定是系统线程快啊,但是你 CPU 跑满的东西你用 go 写?',ipRegion:'',updatedByUid:0,createdAt:'2025-03-22 03:36:12',updatedAt:'2025-03-26 13:48:59',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},],usersMap:new Map([[2910,{uid:2910,url:'/u/3108431a6a045c75696b566f4e5f6628',avatar:'/a/3108431a6a045c75696b566f4e5f6628',username:'ly841000🤖',}],[701,{uid:701,url:'/u/200446196a045c77676a576f455e2b3e',avatar:'/a/200446196a045c77676a576f455e2b3e',username:'huluhulu🤖',}],[849,{uid:849,url:'/u/1f187e076a045c77686e5f6f141b172d',avatar:'/a/1f187e076a045c77686e5f6f141b172d',username:'strobber16🤖',}],[13105,{uid:13105,url:'/u/1127433e6a045d74616a536f200c1f7e',avatar:'/a/1127433e6a045d74616a536f200c1f7e',username:'lance6716🤖',}],[713,{uid:713,url:'/u/163364006a045c77676b556f323d1f1d',avatar:'/a/163364006a045c77676b556f323d1f1d',username:'qxdo1234🤖',}],[13637,{uid:13637,url:'/u/110b4a036a045d746669516f33332510',avatar:'/a/110b4a036a045d746669516f33332510',username:'CEBBCAT🤖',}],[2853,{uid:2853,url:'/u/371f050b6a045c75686f556f001f110a',avatar:'/a/371f050b6a045c75686f556f001f110a',username:'bronyakaka🤖',}],[58,{uid:58,url:'/u/6c314b256a045c77606f5e6f032a181e',avatar:'/a/6c314b256a045c77606f5e6f032a181e',username:'sagaxu🤖',}],[570,{uid:570,url:'/u/3e3a6a5d6a045c77656d566f0f2e3b36',avatar:'/a/3e3a6a5d6a045c77656d566f0f2e3b36',username:'MrKrabs🤖',}],[433,{uid:433,url:'/u/083a7f206a045c776469556f2d1e061e',avatar:'/a/083a7f206a045c776469556f2d1e061e',username:'kneo🤖',}],[5864,{uid:5864,url:'/u/3e180a356a045c72686c526f031c1a28',avatar:'/a/3e180a356a045c72686c526f031c1a28',username:'Donahue🤖',}],[2497,{uid:2497,url:'/u/12397d176a045c756463516f010d2222',avatar:'/a/12397d176a045c756463516f010d2222',username:'sardina🤖',}],[10904,{uid:10904,url:'/u/200b67016a045d77696a526f3f063770',avatar:'/a/200b67016a045d77696a526f3f063770',username:'NotLongNil🤖',}],[140,{uid:140,url:'/u/2e317f3e6a045c77616e566f45116522',avatar:'/a/2e317f3e6a045c77616e566f45116522',username:'cnbatch🤖',}],[9520,{uid:9520,url:'/u/3d1d0a5c6a045c7e6568566f0f331b0f',avatar:'/a/3d1d0a5c6a045c7e6568566f0f331b0f',username:'kingcanfish🤖',}],[2611,{uid:2611,url:'/u/3b3a40016a045c75666b576f4125121d',avatar:'/a/3b3a40016a045c75666b576f4125121d',username:'w568w🤖',}],[14180,{uid:14180,url:'/u/223b5d216a045d736162566f3b2e0437',avatar:'/a/223b5d216a045d736162566f3b2e0437',username:'lxdlam🤖',}],[2745,{uid:2745,url:'/u/2b1166546a045c75676e536f320f1533',avatar:'/a/2b1166546a045c75676e536f320f1533',username:'dearmymy🤖',}],[11135,{uid:11135,url:'/u/6f2d60146a045d766169536f013a0502',avatar:'/a/6f2d60146a045d766169536f013a0502',username:'so1n🤖',}],]),related:[{title:'大佬们平时都是怎样调试查看变量变化的? go 有哪些方便实时展示变量的库或工具?',url:'/d/221f67216a045c77606a567a455c636a23050963',},{title:'c++调试遇到奇怪问题',url:'/d/2e707d5d6a045c77606a567a4658616a28306b21',},{title:'求推荐 C++ 高性能的 web 框架, curd 用',url:'/d/1431451d6a045c77606a56754f51616a07712204',},{title:'Cursor Go 开发,有哪些必装的插件?',url:'/d/337a733f6a045c77606a56754f5b6b6a39061e13',},{title:'在 Go 项目里,涉及到金额计算,大家一般用什么方式?',url:'/d/30267d146a045c77606a5675425d606a3f732227',},{title:'[全职]广州 - 潮汐 App - Golang 开发工程师',url:'/d/022a75356a045c77606a5675445d666a3b301504',},{title:'goland 如何远程开发?',url:'/d/1e1845056a045c77606a56754550676a29726b65',},{title:'开发了一个开箱即用的本地终端 Ztty',url:'/d/0c045a2e6a045c77606a5675455e6b6a3e200734',},{title:'go 部署到 1panel 上,是用源码运行 还是编译二进制运行!',url:'/d/193a435c6a045c77606a5675455c626a38360005',},{title:'[go 分布式定时任务框架] xxljob',url:'/d/357904216a045c77606a5675475f636a041a1663',},{title:'[全职招聘]C++精通 QT 开发',url:'/d/3e1e59396a045c77606a56744f586b6a140c1565',},{title:'关于 Go 并发获取数据的问题,请教大家',url:'/d/687d67226a045c77606a5674415b646a1d3a3138',},{title:'重复造轮子了,用 c++写了个类 rustdesk demo 版本',url:'/d/347171556a045c77606a5674425b616a3f09301d',},{title:'macOS Goland 经常在双击 shift 全局搜索的时候,出现彩虹球,只能强制退出',url:'/d/380f58206a045c77606a5674435b666a15111c2a',},{title:'C++ 开发不想 996,如何跳槽转到 Java ?',url:'/d/09207c086a045c77606a56744358646a1f292613',},{title:'Java 和 go 都会,以后找工作偏向哪个方面好呢',url:'/d/000b7b1b6a045c77606a5674445e656a1977262a',},{title:'作为一个传统开发者,如何使用 ai 或者机器学习实现一些简单事情',url:'/d/34015f186a045c77606a5674445e626a25016611',},{title:'大家 golang 项目里目前在用哪个 log 库打印日志呢?',url:'/d/623a67086a045c77606a5674455c646a5d0c1f65',},{title:'朋友们,有哪些基于 Gin 框架的优秀开源项目,用来学习?',url:'/d/28116a596a045c77606a5674455d656a3c326135',},{title:'新手提问, Go 作为一个 GC 语言,为什么要设计成带指针类型的呢?',url:'/d/12067f176a045c77606a5674455b626a072a2734',},],} const App={setup(){const goTo=useGoTo() const{mdAndUp}=useDisplay() return{goTo,mdAndUp}},data(){return data;},mounted(){const themeDark=localStorage.getItem("themeDark") if(themeDark!==null){this.theme.dark=JSON.parse(themeDark)} if(this.nav.post.total>(this.nav.post.currentPage-1)*100+20){let moreLen=100 if(this.nav.post.total({id:null,num:(this.nav.post.currentPage-1)*100+v,uid:null,content:null,ipRegion:null,updatedByUid:null,createdAt:null,updatedAt:null,mentionNum:null,mentionedBy:null,mentionUsers:null,likeUsers:null,})) this.posts.push(...morePosts.slice(20))} this.workerStart() const hash=window.location.hash const match=hash.match(/#(\d+)/) if(match){const n=parseInt(match[1],10) if(n>=(this.nav.post.currentPage-1)*100&&n{this.jumpTo(n)})}} this.$nextTick(()=>{this.addHeadingIds() tocbot.init({tocSelector:'.toc',contentSelector:'#post-content-0',headingSelector:'h2, h3, h4',headingsOffset:100,scrollSmoothOffset:-100,scrollSmooth:true,collapseDepth:6,onClick:function(e){setTimeout(()=>{history.replaceState(null,'',window.location.pathname+window.location.search)},0)},}) tocbot.refresh()});},beforeUnmount(){this.workerStop() if(this.quill){this.quill.destroy() this.quill=null}},computed:{dposts(){return this.posts.slice(20);},},created(){},methods:{successAlert(msg){this.alert={show:true,color:'success',text:msg,timeout:1500,}},failureAlert(msg){this.alert={show:true,color:'error',text:msg,timeout:5000,}},flipThemeDark(){this.theme.dark=!this.theme.dark localStorage.setItem("themeDark",JSON.stringify(this.theme.dark))},toSearch(){if(!this.search.text){this.failureAlert('搜索词不能为空') return} let keywords=this.search.text.trim() if(keywords.length<1){this.failureAlert('搜索词不能为空') return} if(keywords.length>100){this.failureAlert('搜索词过长') return} this.doSearch(keywords)},toReg(){window.location.href="/reg"},toLogin(){window.location.href="/login"},toPage(){let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,this.nav.post.targetPage>1?`/${this.nav.post.targetPage}`:'') window.location.href=url},toLoadRelated({done}){if(this.my&&this.my.uid){this.apiLoadRelated({done})}else{done('ok')}},workerStart(){this.nav.post.worker=setInterval(()=>{this.workerLoad()},500);},workerStop(){if(this.nav.post.worker){clearInterval(this.nav.post.worker);this.nav.post.worker=null;}},async jumpTo(num){const page=Math.floor(num/100)+1 const i=num-(page-1)*100 if(page===this.nav.post.currentPage){this.goTo("#post-"+num,this.nav.post.goToOptions) if(!this.posts[i].id){const block=Math.floor(num/20)+1 this.nav.post.apiLock[block]=true await this.apiLoadPosts(block) this.$nextTick(()=>{this.goTo("#post-"+num,this.nav.post.goToOptions)})}}else{let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,page>1?`/${page}`:'') url=url+"#"+num window.location.href=url}},postIntersect(num){return(isIntersecting,entries,observer)=>{if(isIntersecting){this.nav.post.task.push(num) this.nav.post.active.push(num) this.nav.post.active=this.nav.post.active.filter(item=>Math.abs(item-num)<=5) this.nav.post.active.sort((a,b)=>a-b)}else{this.nav.post.active=this.nav.post.active.filter(item=>item!==num)} if(this.nav.post.active[0]){this.nav.post.anchor=this.nav.post.active[0]}else{this.nav.post.anchor=0}}},async apiLoadPosts(block){try{const response=await axios.post('/fapi/v1/post/block/'+block,{discussionId:this.nav.post.discussionId,}) if(response.data.code===0){response.data.data.posts.forEach(post=>{const i=post.num%100 Object.assign(this.posts[i],post)}) response.data.data.users.forEach(user=>{this.usersMap.set(user.uid,user)})}else{this.failureAlert('回帖数据加载失败: '+response.data.msg)}}catch(error){this.failureAlert('回帖数据加载失败: '+error)} this.nav.post.apiLock[block]=false},workerLoad(){while(this.nav.post.task.length){const num=this.nav.post.task.pop() const i=num-(this.nav.post.currentPage-1)*100 if(!this.posts[i].id){const block=Math.floor(num/20)+1 if(!this.nav.post.apiLock[block]){this.nav.post.apiLock[block]=true this.apiLoadPosts(block)}}}},getTimeInfo(t){if(!t){return ""} const now=new Date();const then=new Date(t);const diff=now-then;const minute=60*1000;const hour=minute*60;const day=hour*24;const month=day*30;const year=month*12;if(diffpost.num===num) if(!post){return "#"+num} const uid=post.uid const username=this.usersMap.get(uid)?.username if(!username){return "#"+num} return username},getUsernameByPostId(id){const post=this.posts.find(post=>post.id===id) if(!post){return "#"+this.getPostNumByPostId(id)} const uid=post.uid const username=this.usersMap.get(uid).username if(!username){return "#"+this.getPostNumByPostId(id)} return username},getPostNumByPostId(id){const post=this.posts.find(post=>post.id===id) return post.num},getPostById(id){const post=this.posts.find(post=>post.id===id) return post},getPostByNum(num){const post=this.posts.find(post=>post.num===num) return post},getAvatarByUid(uid){const avatar=this.usersMap.get(uid)?.avatar if(!avatar){return this.getRandomAvatar()} return avatar},getAvatarByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post){return this.getRandomAvatar()} const uid=post.uid return this.getAvatarByUid(uid)},getRandomAvatar(){const num=Math.floor(Math.random()*100) return "https://randomuser.me/api/portraits/men/"+num+".jpg"},getUrlByUid(uid){const url=this.usersMap.get(uid)?.url if(!url){return ""} return url},getTextByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post||!post.content){return '点击跳转到#'+num+'查看'} const parser=new DOMParser() const doc=parser.parseFromString(post.content,'text/html') const text=doc.body.textContent||'' return text.slice(0,100)},addHeadingIds(){const content=document.getElementById('post-content-0') if(!content){this.nav.showTOC=false return} const headings=content.querySelectorAll('h2, h3, h4') headings.forEach((heading,index)=>{if(!heading.id){heading.id=`toc-nav-${index}`}}) if(headings.length==0){this.nav.showTOC=false}},async doSearch(keywords){this.search.loading=true try{const response=await axios.post('/fapi/v1/search',{keywords:keywords,}) if(response.data.code===0){if(response.data.data.hash&&response.data.data.hash.length===32){window.location.href="/s/"+response.data.data.hash}else{this.failureAlert('搜索失败: 搜索服务异常')}}else{this.failureAlert('搜索失败: '+response.data.msg)}}catch(error){this.failureAlert('搜索失败: '+error)} this.search.loading=false},debounce(fn,delay){let timer=null return function(...args){if(timer)clearTimeout(timer) timer=setTimeout(()=>{fn.apply(this,args)},delay);};},},watch:{'nav.post.targetPage':{handler:async function(newV,oldV){this.toPage()},immediate:false},},} const vuetify=createVuetify({defaults:{global:{ripple:true,},},}) const app=createApp(App) app.use(vuetify).mount("#app")