直观理解同步和异步的例子
请看一个示例:
同步方式请求接口
请求一次接口耗时大约100多毫秒
代码
一个for循环,循环500次,调用方法Reuest,Reuest方法中一个while(true)无限循环,同步方式请求url获取数据。
代码点评:要是写一个while(true)没问题,这是想运行500个while(true),这代码是错误的,行不通。应该使用Thread或者Task.Run加TaskCreationOptions.LongRunning参数。
这当然是有问题的代码,请看下面运行截图,只有第一个while(true)在执行,其它的499个while(true)根本没有执行机会。
static int num = 0;
static ConcurrentDictionary<int, object> dict = new ConcurrentDictionary<int, object>();
static void Main(string[] args)
{
CalcSpeed();
for (int i = 0; i < 500; i++)
{
Reuest(i);
}
Console.WriteLine($"Main函数结束");
Console.ReadLine();
}
static void Reuest(int index)
{
dict.TryAdd(index, null);
while (true)
{
string url = "http://localhost:5028/Test/TestGet";
string result = HttpUtil.HttpGet(url);
Interlocked.Increment(ref num);
}
}
static void CalcSpeed()
{
_ = Task.Factory.StartNew(() =>
{
Stopwatch sw = Stopwatch.StartNew();
while (true)
{
Thread.Sleep(2000);
double speed = num / sw.Elapsed.TotalSeconds;
ThreadPool.GetMaxThreads(out int w1, out int c1);
ThreadPool.GetAvailableThreads(out int w2, out int c2);
Console.WriteLine($"有 {dict.Count.ToString().PadLeft(3)} 个 while(true) 在执行,线程池活动线程数:{(w1 - w2).ToString().PadRight(3)} 速度:{speed:#### ####.0} 次/秒");
}
}, TaskCreationOptions.LongRunning);
}
运行截图
说明
代码中没有创建线程,也没有使用Task.Run,请求一次接口耗时大约100多毫秒,while(true)在主线程中执行,平均1秒请求接口不到10次。
注意:只有第一个while(true)在执行。
修改1:在Reuest函数中添加一行代码Thread.Sleep(1);
代码
static void Reuest(int index)
{
dict.TryAdd(index, null);
while (true)
{
string url = "http://localhost:5028/Test/TestGet";
string result = HttpUtil.HttpGet(url);
Interlocked.Increment(ref num);
Thread.Sleep(1);
}
}
运行截图
说明
没什么用,速度还变慢了一点。
依然是有问题的代码。
依然只有第一个while(true)在执行。
修改2:在Reuest函数中添加一行代码await Task.Delay(1);
VS自动在void Reuest前面添加了async关键字
代码
static async void Reuest(int index)
{
dict.TryAdd(index, null);
while (true)
{
string url = "http://localhost:5028/Test/TestGet";
string result = HttpUtil.HttpGet(url);
Interlocked.Increment(ref num);
await Task.Delay(1);
}
}
运行截图
说明
速度快多了,并且越来越快。
有多个while(true)在执行,并且在执行的while(true)数量越来越多,最终会达到500个。
这是比较神奇的地方,仅仅加了一行await Task.Delay(1);同步方法Request就变成了异步方法。
在执行await Task.Delay(1);这一行时,其它while(true)得到了执行机会,你们可以验证一下。
同步请求分别在不同的线程中执行,你们可以打印线程ID验证一下。
修改3:前面使用的是HttpUtil.HttpGet同步请求,修改为异步请求,await Task.Delay(1);这一行也不需要了
代码
static async void Reuest(int index)
{
dict.TryAdd(index, null);
while (true)
{
string url = "http://localhost:5028/Test/TestGet";
var httpClient = HttpClientFactory.GetClient();
string result = await (await httpClient.GetAsync(url)).Content.ReadAsStringAsync();
Interlocked.Increment(ref num);
}
}
运行截图
说明
速度非常快。
异步的优势体现出来了。
修改4:有没有人会认为修改2,把同步代码用Task.Run包一下,速度会更快?
代码
static async void Reuest(int index)
{
dict.TryAdd(index, null);
while (true)
{
await Task.Run(() =>
{
string url = "http://localhost:5028/Test/TestGet";
string result = HttpUtil.HttpGet(url);
Interlocked.Increment(ref num);
});
await Task.Delay(1);
}
}
运行截图
说明
线程饥饿,全部阻塞,没有返回结果,速度是0。
总结
通过这个例子形象地体会一下同步与异步,以及为什么要使用异步。
如果你写的代码是异步的,但是调用的IO接口又是同步的,这比真正的异步效率要差很多,但比同步代码有所提升。
针对修改2,有人会说,这代码有问题,后面的while(true)会延迟好久才会执行。但是如果for循环的数量是少量的,程序启动时的一点延迟是允许的,就没有问题,
修改代码如下:
for (int i = 0; i < 20; i++)
{
Reuest(i);
}
运行截图:
说明:
20个while(true)都在运行,比一个while(true)要快很多。
当然,没必要这么写了,直接new 20个Thread就可以。
但如果for循环就是500次,而且需要调用的IO接口又是同步的,那么就老老实实写500个new Thread。
如果非要用异步,设置一下线程池的大小,大于500,避免线程饥饿。
ThreadPool.SetMinThreads(800, 800);
ThreadPool.SetMinThreads(600, 600);
你会发现,不能想当然,依然有问题,这时强行用异步就很容易写出BUG了。
推荐阅读
-
epoll简介及触发模式(accept、read、send)-epoll的简单介绍 epoll在LT和ET模式下的读写方式 一、epoll的接口非常简单,一共就三个函数:1. int epoll_create(int size);创建一个epoll的句柄,size用来告诉内核这个监听的数目一共有多大。这个参数不同于select中的第一个参数,给出最大监听的fd+1的值。需要注意的是,当创建好epoll句柄后,它就是会占用一个fd值,在linux下如果查看/proc/进程id/fd/,是能够看到这个fd的,所以在使用完epoll后,必须调用close关闭,否则可能导致fd被耗尽。2. int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);epoll的事件注册函数,它不同与select是在监听事件时告诉内核要监听什么类型的事件,而是在这里先注册要监听的事件类型。第一个参数是epoll_create的返回值,第二个参数表示动作,用三个宏来表示:EPOLL_CTL_ADD:注册新的fd到epfd中;EPOLL_CTL_MOD:修改已经注册的fd的监听事件;EPOLL_CTL_DEL:从epfd中删除一个fd;第三个参数是需要监听的fd,第四个参数是告诉内核需要监听什么事,struct epoll_event结构如下:struct epoll_event { __uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */};events可以是以下几个宏的集合:EPOLLIN :表示对应的文件描述符可以读(包括对端SOCKET正常关闭); EPOLLIN事件:EPOLLIN事件则只有当对端有数据写入时才会触发,所以触发一次后需要不断读取所有数据直到读完EAGAIN为止。否则剩下的数据只有在下次对端有写入时才能一起取出来了。现在明白为什么说epoll必须要求异步socket了吧?如果同步socket,而且要求读完所有数据,那么最终就会在堵死在阻塞里。 EPOLLOUT:表示对应的文件描述符可以写; EPOLLOUT事件:EPOLLOUT事件只有在连接时触发一次,表示可写,其他时候想要触发,那要先准备好下面条件:1.某次write,写满了发送缓冲区,返回错误码为EAGAIN。2.对端读取了一些数据,又重新可写了,此时会触发EPOLLOUT。简单地说:EPOLLOUT事件只有在不可写到可写的转变时刻,才会触发一次,所以叫边缘触发,这叫法没错的!其实,如果真的想强制触发一次,也是有办法的,直接调用epoll_ctl重新设置一下event就可以了,event跟原来的设置一模一样都行(但必须包含EPOLLOUT),关键是重新设置,就会马上触发一次EPOLLOUT事件。1. 缓冲区由满变空.2.同时注册EPOLLIN | EPOLLOUT事件,也会触发一次EPOLLOUT事件这个两个也会触发EPOLLOUT事件 EPOLLPRI:表示对应的文件描述符有紧急的数据可读(这里应该表示有带外数据到来);EPOLLERR:表示对应的文件描述符发生错误;EPOLLHUP:表示对应的文件描述符被挂断;EPOLLET: 将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(Level Triggered)来说的。EPOLLONESHOT:只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里3. int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);等待事件的产生,类似于select调用。参数events用来从内核得到事件的集合,maxevents告之内核这个events有多大,这个maxevents的值不能大于创建epoll_create时的size,参数timeout是超时时间(毫秒,0会立即返回,-1将不确定,也有说法说是永久阻塞)。该函数返回需要处理的事件数目,如返回0表示已超时。-------------------------------------------------------------------------------------------- 从man手册中,得到ET和LT的具体描述如下EPOLL事件有两种模型:Edge Triggered (ET)Level Triggered (LT)假如有这样一个例子:1. 我们已经把一个用来从管道中读取数据的文件句柄(RFD)添加到epoll描述符2. 这个时候从管道的另一端被写入了2KB的数据3. 调用epoll_wait(2),并且它会返回RFD,说明它已经准备好读取操作4. 然后我们读取了1KB的数据5. 调用epoll_wait(2)......Edge Triggered 工作模式:如果我们在第1步将RFD添加到epoll描述符的时候使用了EPOLLET标志,那么在第5步调用epoll_wait(2)之后将有可能会挂起,因为剩余的数据还存在于文件的输入缓冲区内,而且数据发出端还在等待一个针对已经发出数据的反馈信息。只有在监视的文件句柄上发生了某个事件的时候 ET 工作模式才会汇报事件。因此在第5步的时候,调用者可能会放弃等待仍在存在于文件输入缓冲区内的剩余数据。在上面的例子中,会有一个事件产生在RFD句柄上,因为在第2步执行了一个写操作,然后,事件将会在第3步被销毁。因为第4步的读取操作没有读空文件输入缓冲区内的数据,因此我们在第5步调用 epoll_wait(2)完成后,是否挂起是不确定的。epoll工作在ET模式的时候,必须使用非阻塞套接口,以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死。最好以下面的方式调用ET模式的epoll接口,在后面会介绍避免可能的缺陷。 i 基于非阻塞文件句柄 ii 只有当read(2)或者write(2)返回EAGAIN时才需要挂起,等待。但这并不是说每次read时都需要循环读,直到读到产生一个EAGAIN才认为此次事件处理完成,当read返回的读到的数据长度小于请求的数据长度时,就可以确定此时缓冲中已没有数据了,也就可以认为此事读事件已处理完成。Level Triggered 工作模式相反的,以LT方式调用epoll接口的时候,它就相当于一个速度比较快的poll(2),并且无论后面的数据是否被使用,因此他们具有同样的职能。因为即使使用ET模式的epoll,在收到多个chunk的数据的时候仍然会产生多个事件。调用者可以设定EPOLLONESHOT标志,在 epoll_wait(2)收到事件后epoll会与事件关联的文件句柄从epoll描述符中禁止掉。因此当EPOLLONESHOT设定后,使用带有 EPOLL_CTL_MOD标志的epoll_ctl(2)处理文件句柄就成为调用者必须作的事情。然后详细解释ET, LT:LT(level triggered)是缺省的工作方式,并且同时支持block和no-block socket.在这种做法中,内核告诉你一个文件描述符是否就绪了,然后你可以对这个就绪的fd进行IO操作。如果你不作任何操作,内核还是会继续通知你的,所以,这种模式编程出错误可能性要小一点。传统的select/poll都是这种模型的代表.ET(edge-triggered)是高速工作方式,只支持no-block socket。在这种模式下,当描述符从未就绪变为就绪时,内核通过epoll告诉你。然后它会假设你知道文件描述符已经就绪,并且不会再为那个文件描述符发送更多的就绪通知,直到你做了某些操作导致那个文件描述符不再为就绪状态了(比如,你在发送,接收或者接收请求,或者发送接收的数据少于一定量时导致了一个EWOULDBLOCK 错误)。但是请注意,如果一直不对这个fd作IO操作(从而导致它再次变成未就绪),内核不会发送更多的通知(only once),不过在TCP协议中,ET模式的加速效用仍需要更多的benchmark确认(这句话不理解)。在许多测试中我们会看到如果没有大量的idle -connection或者dead-connection,epoll的效率并不会比select/poll高很多,但是当我们遇到大量的idle- connection(例如WAN环境中存在大量的慢速连接),就会发现epoll的效率大大高于select/poll。(未测试)另外,当使用epoll的ET模型来工作时,当产生了一个EPOLLIN事件后,读数据的时候需要考虑的是当recv返回的大小如果等于请求的大小,那么很有可能是缓冲区还有数据未读完,也意味着该次事件还没有处理完,所以还需要再次读取: 这里只是说明思路(参考《UNIX网络编程》) while(rs) {buflen = recv(activeevents[i].data.fd, buf, sizeof(buf), 0);if(buflen < 0){// 由于是非阻塞的模式,所以当errno为EAGAIN时,表示当前缓冲区已无数据可读// 在这里就当作是该次事件已处理处.if(errno == EAGAIN)break; else return; }else if(buflen == 0) { // 这里表示对端的socket已正常关闭. } if(buflen == sizeof(buf) rs = 1; // 需要再次读取 else rs = 0; } 还有,假如发送端流量大于接收端的流量(意思是epoll所在的程序读比转发的socket要快),由于是非阻塞的socket,那么send函数虽然返回,但实际缓冲区的数据并未真正发给接收端,这样不断的读和发,当缓冲区满后会产生EAGAIN错误(参考man send),同时,不理会这次请求发送的数据.所以,需要封装socket_send的函数用来处理这种情况,该函数会尽量将数据写完再返回,返回-1表示出错。在socket_send内部,当写缓冲已满(send返回-1,且errno为EAGAIN),那么会等待后再重试.这种方式并不很完美,在理论上可能会长时间的阻塞在socket_send内部,但暂没有更好的办法. ssize_t socket_send(int sockfd, const char* buffer, size_t buflen) { ssize_t tmp; size_t total = buflen; const char *p = buffer; while(1) { tmp = send(sockfd, p, total, 0); if(tmp < 0) { // 当send收到信号时,可以继续写,但这里返回-1. if(errno == EINTR) return -1; // 当socket是非阻塞时,如返回此错误,表示写缓冲队列已满, // 在这里做延时后再重试. if(errno == EAGAIN) { usleep(1000); continue; } return -1; } if((size_t)tmp == total) return buflen; total -= tmp; p += tmp; } return tmp; } 二、epoll在LT和ET模式下的读写方式 在一个非阻塞的socket上调用read/write函数, 返回EAGAIN或者EWOULDBLOCK(注: EAGAIN就是EWOULDBLOCK) 从字面上看, 意思是: * EAGAIN: 再试一次 * EWOULDBLOCK: 如果这是一个阻塞socket, 操作将被block * perror输出: Resource temporarily unavailable 总结: 这个错误表示资源暂时不够, 可能read时, 读缓冲区没有数据, 或者, write时,写缓冲区满了 。 遇到这种情况, 如果是阻塞socket, read/write就要阻塞掉。 而如果是非阻塞socket, read/write立即返回-1, 同 时errno设置为EAGAIN. 所以, 对于阻塞socket, read/write返回-1代表网络出错了. 但对于非阻塞socket, read/write返回-1不一定网络真的出错了. 可能是Resource temporarily unavailable. 这时你应该再试, 直到Resource available. 综上, 对于non-blocking的socket, 正确的读写操作为: 读: 忽略掉errno = EAGAIN的错误, 下次继续读 写: 忽略掉errno = EAGAIN的错误, 下次继续写 对于select和epoll的LT模式, 这种读写方式是没有问题的. 但对于epoll的ET模式, 这种方式还有漏洞. epoll的两种模式 LT 和 ET
-
像首席技术官一样思考:如何高效管理 30 人的研发团队?-管理越多越轻松。好的研发团队,应该是上拨下用,即下级对上级的向上管理;而不是反过来,总是向下管理,甚至是 CTO 做经理的事,经理做工程师的事,工程师最终会被当成实习生。如果是这样,就会越管越累,不仅团队无法成长,而且团队整天很忙还效率低下,问题一大堆。 有这样一个小故事:一位高级经理下班后帮忙倒垃圾,结果被老板训斥了一顿。这就好比首席技术官做了实习生自己该做的事。事情本身没有对错之分,只是从不同的角度有不同的理解。 古人云:"用人不疑,疑人不用"。在面对自己的研发团队时,应该相信他们能做好,授权一线开发人员充分发挥专业特长,不要限制他们的工作。但在相信他们的同时,也要进行二次确认,始终秉持 "我相信,但我要确认 "的原则和严谨的精神。因为每个人都会犯错和疏忽,通过发挥团队的智慧,团队犯错的机会就会大大减少。比如回归测试、代码审查、开发演示、变更审批等等。 如前所述,每个人都难免会犯错。但作为管理者,你所设计和商定的流程不能出错。管理者的每一个决定和沟通都应该经过深思熟虑。就像红绿灯的交通设计,某辆车不小心闯红灯可能会扣分,但红绿灯的设计一定要正确、人性化、统一。再比如,开发人员可能会因为疏忽大意写出 bug,但研发流程的设计和上线流程的发布不能有任何差错。因此,流程体系的设计,一方面要结合当前团队规模、业务特点和需要重点解决的问题来设计,另一方面也要在人员防错、效率提升、发挥团队集体智慧等维度进行综合考量。应该站在更高更抽象的角度去思考,不断思考一个倍受欢迎的园区应该如何设计,思考一个灵动、经典、永恒的建筑应该遵循怎样的模式,思考一个成功、优秀、卓越的研发团队应该需要怎样的流程和制度。 最后,反馈很重要。向上汇报很重要,向下反馈也很重要。能够保持顺畅的双向反馈和闭环管理,对研发团队的协作和沟通有着非常明显的积极作用。在向上汇报方面,要培养团队在正式汇报、会议汇报、私下沟通、书面总结、非正式场合等方面的沟通能力,提醒下属报喜也要报忧。凡事先记录,再跟进,最后反馈。反馈很重要,主动汇报更难得。 另一方面,同时也不要忽视向下反馈。好的爱,是双向的。团队也是如此,没有严格的上下级之分,只是分工和角色不同而已。作为管理者,不必总保持一种 "神秘感",让人 "捉摸不透 "才是牛。当团队做得好或有人做得好时,要记得在公开或私下场合给予肯定和赞许。业务有增长、业绩有提升时,别忘了给团队一些鼓励,或者安排一次下午茶或聚餐。在例会或正式会议上,也可以同步向大家传达一些重要信息和高层指示。"欲速则不达,欲远则同行"。 当向上汇报、向下反馈的沟通闭环形成后,同时结合前面研发过程的管理闭环,双管齐下,就能形成良性循环。如此反复,持之以恒,优秀卓越的研发团队,必将呈现。 能力、产出和效率 接下来,继续重复关于能力、产出和效率的话题。 站在不同的角色,以及一个企业经营、生存和发展所需要的基础上,我把研发生产力分为三个层次,分别是:一线员工关心的研发能力、管理层关心的软件产出和操作人员关心的企业生产效率。简单概括就是:既要把工作做好,又要能出成果,还要能帮企业赚钱。
-
Java 线程中对象的同步和异步
-
Kafka 高可用性之谜:深入剖析其架构原理和关键技术--副本数量与分布:适当增加副本数量可以提高容错能力,但会增加网络开销和存储成本。合理分配副本,保证副本在不同Broker上尽可能分散,可以降低单点故障的影响。 数据复制策略:Kafka 支持同步复制(在响应客户端之前同步 ISR 中的所有副本)和异步复制(响应客户端后异步复制到其他副本)。同步复制提供更强的数据一致性,但会牺牲写性能;异步复制则相反。根据业务对一致性和性能的需求,选择合适的复制策略。 监控和报警:实时监控代理、分区和复制状态,设置阈值警报,及时发现并处理异常情况,是保证高可用性的必要条件。 V.总结
-
基于多种设计模式的 C++ 同步和异步日志系统 第 7 天(最终版)
-
统计学习 04:假设检验(以 t 检验为例)和 P 值 - 要点 I. 假设检验的一般思路 假设检验 清楚你的问题是什么?期望得出什么结论? 例如,两种药物的疗效是否存在差异,自变量与因变量之间是否存在回归关系 .... 请始终牢记,假设检验回答的是是否存在某种关系的问题:它并不衡量这种关系有多大。 提出两种假设:零假设 (H0) 和备择假设 (H1) 零假设与备择假设相反,一般来说,研究的目的是证明原假设是错误的,即得出备择假设的结论。 例如,如果实验预期希望两种药物的疗效存在差异,那么 H0:μ1 - μ2 = 0;H1:μ1 - μ2 ≠ 0 H0:μ1-μ2 = 0 的一般形式称为双侧检验,而 >、<等零假设称为单侧检验。一般来说双侧检验更为常见,下面也主要介绍这种方法。 单尾或双尾测试 根据原始数据计算零假设概率分布的统计量(t 值、Z 值、F 值等)。 根据问题的性质选择合适的概率检验方法,从而计算出相应的统计量值;因此,不同情况的统计量值有不同的计算方法。 根据计算出的统计量值,利用统计软件,可以知道相应的 p 值是多少 也可以先确定一个合适的显著性水平(0.0.001....),并计算其临界值,再与我们计算出的统计量值进行比较,从而做出判断。 根据第四步的比较结果,如果 p 值小于预期的显著性水平(α,通常设定为 0.05),则认为该统计量远离原假设分布,属于小概率事件,则拒绝原假设,从而接受备择假设。 决定 要点 2:以 t 检验为例,演示上述假设检验思路。 t 检验基于 t 分布,常见的 t 检验有三种,如下图所示,但我认为第三种配对设计可能更常用(零假设:差异是否为零),下面介绍的例子就是一种配对设计 三次 t 检验 举例测量两组大鼠肝脏中维生素 A 的含量,比较两组大鼠维生素 A 含量是否有差异。数据如下 数据 (1) 预计两组大鼠的维生素 A 水平存在差异 (2) H0:μd=0,H1:μd≠0,α=0.05,双侧检验 (3) t 统计量的计算 配方 计算 上述程序计算的是*度为 7 的 t 分布情况下的 t 值。只需理解公式即可,不同的方法有不同的公式,这些交给统计软件即可。
-
理解电力系统中的同步相量和相位角详解
-
理解JavaScript的运行机制:同步和异步(宏观任务与微观任务)
-
Verilog中的同步和异步设计详解
-
直观理解同步和异步的例子