主頁 > 後端開發 > C基礎 帶你手寫 redis ae 事件驅動模型

C基礎 帶你手寫 redis ae 事件驅動模型

2020-09-16 07:26:12 後端開發

引言 - 整體認識

  redis ae 事件驅動模型, 網上聊得很多. 但當你仔細看完一篇又一篇之后, 可能你看的很舒服, 但對于

作者為什么要這么寫, 出發點, 好處, 缺點 ... 可能還是好模糊, 不是嗎?

我們這里基于閱讀的人已經了解了 IO 復用大致流程且抄寫過 ae 的全部代碼. 好, 那開始吧, 希望后面的

點撥, 給同學們醍醐灌頂一下. 

  先看看 ae.h 設計 

/* A simple event-driven programming library. Originally I wrote this code * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated * it in form of a library for easy reuse. * * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * *   * Redistributions of source code must retain the above copyright notice, *     this list of conditions and the following disclaimer. *   * Redistributions in binary form must reproduce the above copyright *     notice, this list of conditions and the following disclaimer in the *     documentation and/or other materials provided with the distribution. *   * Neither the name of Redis nor the names of its contributors may be used *     to endorse or promote products derived from this software without *     specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */#ifndef __AE_H__#define __AE_H__#include <time.h>#define AE_OK 0#define AE_ERR -1#define AE_NONE 0       /* No events registered. */#define AE_READABLE 1   /* Fire when descriptor is readable. */#define AE_WRITABLE 2   /* Fire when descriptor is writable. */#define AE_BARRIER 4    /* With WRITABLE, never fire the event if the                           READABLE event already fired in the same event                           loop iteration. Useful when you want to persist                           things to disk before sending replies, and want                           to do that in a group fashion. */#define AE_FILE_EVENTS 1#define AE_TIME_EVENTS 2#define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS)#define AE_DONT_WAIT 4#define AE_CALL_AFTER_SLEEP 8#define AE_NOMORE -1#define AE_DELETED_EVENT_ID -1/* Macros */#define AE_NOTUSED(V) ((void) V)struct aeEventLoop;/* Types and data structures */typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask);typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData);typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData);typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop);/* File event structure */typedef struct aeFileEvent {    int mask; /* one of AE_(READABLE|WRITABLE|BARRIER) */    aeFileProc *rfileProc;    aeFileProc *wfileProc;    void *clientData;} aeFileEvent;/* Time event structure */typedef struct aeTimeEvent {    long long id; /* time event identifier. */    long when_sec; /* seconds */    long when_ms; /* milliseconds */    aeTimeProc *timeProc;    aeEventFinalizerProc *finalizerProc;    void *clientData;    struct aeTimeEvent *prev;    struct aeTimeEvent *next;} aeTimeEvent;/* A fired event */typedef struct aeFiredEvent {    int fd;    int mask;} aeFiredEvent;/* State of an event based program */typedef struct aeEventLoop {    int maxfd;   /* highest file descriptor currently registered */    int setsize; /* max number of file descriptors tracked */    long long timeEventNextId;    time_t lastTime;     /* Used to detect system clock skew */    aeFileEvent *events; /* Registered events */    aeFiredEvent *fired; /* Fired events */    aeTimeEvent *timeEventHead;    int stop;    void *apidata; /* This is used for polling API specific data */    aeBeforeSleepProc *beforesleep;    aeBeforeSleepProc *aftersleep;    int flags;} aeEventLoop;/* Prototypes */aeEventLoop *aeCreateEventLoop(int setsize);void aeDeleteEventLoop(aeEventLoop *eventLoop);void aeStop(aeEventLoop *eventLoop);int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,        aeFileProc *proc, void *clientData);void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask);int aeGetFileEvents(aeEventLoop *eventLoop, int fd);long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,        aeTimeProc *proc, void *clientData,        aeEventFinalizerProc *finalizerProc);int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id);int aeProcessEvents(aeEventLoop *eventLoop, int flags);int aeWait(int fd, int mask, long long milliseconds);void aeMain(aeEventLoop *eventLoop);char *aeGetApiName(void);void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep);void aeSetAfterSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *aftersleep);int aeGetSetSize(aeEventLoop *eventLoop);int aeResizeSetSize(aeEventLoop *eventLoop, int setsize);void aeSetDontWait(aeEventLoop *eventLoop, int noWait);#endif

很多朋友首次看, 或者第一次手寫完畢 ae.h 結構設計檔案, 印象里 60% 是模糊不可描述 ~ 也許大致知

道這宏有點感覺應該是和 IO Event 事件有關吧 ... 

我這里先稍微要劇透點, 帶大家快速了解這個庫的結構設計的意圖. C 先看結構, 比先看介面設計更容

易獲取到核心資訊. 上面代碼中最重要四個結構分別是

  aeFileEvent, aeTimeEvent, aeFiredEvent, aeEventLoop

aeFileEvent 是檔案描述符 Event, 注冊在 aeEventLoop 中, 當觸發后會生成事件結構 aeFiredEvent,

用于后續處理.  aeTimeEvent 是 timer Event 同樣注冊在  aeEventLoop 中用于觸發定時事件. (太懶,

懶畫圖, 有興趣朋友可以自行理解畫出好理解的圖) 對于  aeEventLoop 內部欄位的設計,  先不劇透了. 

后面正文部分會討論一些. 

前言 - 底層解密

  ae 檔案整體結構如下

很清晰的看出 epoll, evport, kqueue, select IO 復用的核心包裝. 但寫完整個 ae.c 發現對其設計影響

最深可能就是 ae_select.c 中兼容 select 思路.

/* Select()-based ae.c module. * * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * *   * Redistributions of source code must retain the above copyright notice, *     this list of conditions and the following disclaimer. *   * Redistributions in binary form must reproduce the above copyright *     notice, this list of conditions and the following disclaimer in the *     documentation and/or other materials provided with the distribution. *   * Neither the name of Redis nor the names of its contributors may be used *     to endorse or promote products derived from this software without *     specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */#include <sys/select.h>#include <string.h>typedef struct aeApiState {    fd_set rfds, wfds;    /* We need to have a copy of the fd sets as it's not safe to reuse     * FD sets after select(). */    fd_set _rfds, _wfds;} aeApiState;static int aeApiCreate(aeEventLoop *eventLoop) {    aeApiState *state = zmalloc(sizeof(aeApiState));    if (!state) return -1;    FD_ZERO(&state->rfds);    FD_ZERO(&state->wfds);    eventLoop->apidata =https://www.cnblogs.com/life2refuel/p/ state;    return 0;}static int aeApiResize(aeEventLoop *eventLoop, int setsize) {    /* Just ensure we have enough room in the fd_set type. */    if (setsize >= FD_SETSIZE) return -1;    return 0;}static void aeApiFree(aeEventLoop *eventLoop) {    zfree(eventLoop->apidata);}static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {    aeApiState *state = eventLoop->apidata;    if (mask & AE_READABLE) FD_SET(fd,&state->rfds);    if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds);    return 0;}static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) {    aeApiState *state = eventLoop->apidata;    if (mask & AE_READABLE) FD_CLR(fd,&state->rfds);    if (mask & AE_WRITABLE) FD_CLR(fd,&state->wfds);}static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {    aeApiState *state = eventLoop->apidata;    int retval, j, numevents = 0;    memcpy(&state->_rfds,&state->rfds,sizeof(fd_set));    memcpy(&state->_wfds,&state->wfds,sizeof(fd_set));    retval = select(eventLoop->maxfd+1,                &state->_rfds,&state->_wfds,NULL,tvp);    if (retval > 0) {        for (j = 0; j <= eventLoop->maxfd; j++) {            int mask = 0;            aeFileEvent *fe = &eventLoop->events[j];            if (fe->mask == AE_NONE) continue;            if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds))                mask |= AE_READABLE;            if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds))                mask |= AE_WRITABLE;            eventLoop->fired[numevents].fd = j;            eventLoop->fired[numevents].mask = mask;            numevents++;        }    }    return numevents;}static char *aeApiName(void) {    return "select";}

作者實作這個 select 思路不是很好, 他把 ae_select.c 當做區域檔案去設計, 沒有想拆出來獨擋一面.

其次對于 select 的第四個引數 error fds 集合沒有處理(ae_epoll.c 中 EPOLLHUB 和 EPOLLERR 是

處理). 實作層面 aeApiPoll 也不夠好, 推薦采用下面實作 

#include "ae.h"#include <string.h>#include <sys/select.h>static int aeApiPoll(aeEventLoop * eventLoop, struct timeval * tvp) {    aeApiState * state = eventLoop->apidata;    int retval, j, numevents = 0;    memcpy(&state->_rfds, &state->rfds, sizeof(fd_set));    memcpy(&state->_wfds, &state->wfds, sizeof(fd_set));    retval = select(eventLoop->maxfd+1, &state->_rfds, &state->_wfds, NULL, tvp);    for (j = 0; j <= eventLoop->maxfd && numevents < retval; j++) {        int mask = AE_NONE;        aeFileEvent * fe = &eventLoop->events[j];        if (fe->mask == AE_NONE) continue;        if (fe->mask & AE_READABLE && FD_ISSET(j, &state->_rfds))            mask |= AE_READABLE;        if (fe->mask & AE_WRITABLE && FD_ISSET(j, &state->_wfds))            mask |= AE_WRITABLE;        if (mask == AE_NONE) continue;        eventLoop->fired[numevents].fd = j;        eventLoop->fired[numevents].mask = mask;        numevents++;    }    return numevents;}

降低不需要處理的 AE_NONE 空事件.  隨后的 epoll kqueue 都差不多(evport 不熟, 有心的朋友也別看)

正文 - 細節點撥

  整體看 ae 事件模型設計, 還是有些簡陋的. 我猜測是 redis 重IO和記憶體操作, 對很多檔案描述符需求

較固定,  一個檔案描述符多數自始至終. 應對的場景不是那種大量的創建, 互動, 關閉. 所以整體設計也能

接受.

1.  setsize maxfd event fired 到底想表達什么?

#include <time.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <poll.h>#include <unistd.h>#include <sys/time.h>#include <sys/types.h>#include "ae.h"#include "config.h"#include "zmalloc.h"/* Include the best multiplexing layer supported by this system. * The following should be ordered by performances, descending. */#ifdef HAVE_EVPORT#include "ae_evport.c"#else    #ifdef HAVE_EPOLL    #include "ae_epoll.c"    #else        #ifdef HAVE_KQUEUE        #include "ae_epoll.c"        #else        #include "ae_select.c"        #endif    #endif#endifaeEventLoop * aeCreateEventLoop(int setsize) {    aeEventLoop * eventLoop;    int i;    if (!(eventLoop = zmalloc(sizeof(*eventLoop)))) goto err;    eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize);    eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize);    if (!eventLoop->events || !eventLoop->fired) goto err;    eventLoop->setsize = setsize;    eventLoop->lastTime = time(NULL);    eventLoop->timeEventHead = NULL;    eventLoop->timeEventNextId = 0;    eventLoop->stop = 0;    eventLoop->maxfd = -1;    eventLoop->beforesleep = NULL;    eventLoop->aftersleep = NULL;    eventLoop->flags = 0;    if (aeApiCreate(eventLoop) == -1) goto err;    /* Events with mask == AE_NONE are not set. So let's initialize the     * vector with it. */    for (i = 0; i < setsize; i++)        eventLoop->events[i].mask = AE_NONE;    return eventLoop;err:    if (eventLoop) {        zfree(eventLoop->events);        zfree(eventLoop->fired);        zfree(eventLoop);    }    return NULL;}

有心的同學可以關注  eventLoop->events 和 eventLoop->fired zmalloc 這塊, 這基本已經

把之前的 ae_select.c ae_epoll.c ae_kqueue.c ... 串起來了. 分別用于存要監控的事件和有變動的事件.

對于 setsize 也是個看點我們分別看 server.c server.h config.c 區域代碼

[server.c] server.el = aeCreateEventLoop(server.maxclients+CONFIG_FDSET_INCR);[server.h]#define CONFIG_MIN_RESERVED_FDS 32/* When configuring the server eventloop, we setup it so that the total number* of file descriptors we can handle are server.maxclients + RESERVED_FDS +* a few more to stay safe. Since RESERVED_FDS defaults to 32, we add 96* in order to make sure of not over provisioning more than 128 fds. */#define CONFIG_FDSET_INCR (CONFIG_MIN_RESERVED_FDS+96)[config.c]/* Unsigned int configs */createUIntConfig("maxclients", NULL, MODIFIABLE_CONFIG, 1, UINT_MAX, server.maxclients, 10000, INTEGER_CONFIG, NULL, updateMaxclients),

可以看出來 setsize 分為兩部分, 一分部分是配置的, 默認是 10000; 另外一部分是預留 128個. 

(128 分為兩部分 CONFIG_MIN_RESERVED_FDS = 32 + 96, 前者是 redis fd 保留的最少個數)

和上面 aeCreateEventLoop 相似的功能有 aeResizeSetSize 

/* Resize the maximum set size of the event loop. * If the requested set size is smaller than the current set size, but * there is already a file descriptor in use that is >= the requested * set size minus one, AE_ERR is returned and the operation is not * performed at all. * * Otherwise AE_OK is returned and the operation is successful. */int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) {    int i;    if (setsize == eventLoop->setsize) return AE_OK;    if (eventLoop->maxfd >= setsize) return AE_ERR;    if (aeApiResize(eventLoop,setsize) == -1) return AE_ERR;    eventLoop->events = zrealloc(eventLoop->events,sizeof(aeFileEvent)*setsize);    eventLoop->fired = zrealloc(eventLoop->fired,sizeof(aeFiredEvent)*setsize);    eventLoop->setsize = setsize;    /* Make sure that if we created new slots, they are initialized with     * an AE_NONE mask. */    for (i = eventLoop->maxfd+1; i < setsize; i++)        eventLoop->events[i].mask = AE_NONE;    return AE_OK;}

透過這兩個函式希望你對 aeEventLoop 中 setsize maxfd event fired 這些欄位能了解透徹. 

2. aeTimeEvent 怎么用, 怎么設計的?

redis 中 timer Event 設計比較簡單, 單純的無序時間鏈表. 下面這段作者意圖表達的很清晰. 

/* Search the first timer to fire. * This operation is useful to know how many time the select can be * put in sleep without to delay any event. * If there are no timers NULL is returned. * * Note that's O(N) since time events are unsorted. * Possible optimizations (not needed by Redis so far, but...): * 1) Insert the event in order, so that the nearest is just the head. *    Much better but still insertion or deletion of timers is O(N). * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)). */static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop){    aeTimeEvent *te = eventLoop->timeEventHead;    aeTimeEvent *nearest = NULL;    while(te) {        if (!nearest || te->when_sec < nearest->when_sec ||                (te->when_sec == nearest->when_sec &&                 te->when_ms < nearest->when_ms))            nearest = te;        te = te->next;    }    return nearest;}

而其中到底怎么跑起來的呢, 我截取 processTimeEvents 中部分代碼, 幫讀者了然于心

/* Process time events */static int processTimeEvents(aeEventLoop *eventLoop) {    int processed = 0;    aeTimeEvent *te;    long long maxId;    time_t now = time(NULL);...  {        ...        aeGetTime(&now_sec, &now_ms);        if (now_sec > te->when_sec ||            (now_sec == te->when_sec && now_ms >= te->when_ms))        {            int retval;            id = te->id;            retval = te->timeProc(eventLoop, id, te->clientData);            processed++;            if (retval != AE_NOMORE) {                aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);            } else {                te->id = AE_DELETED_EVENT_ID;            }        }        ...        }   ...    return processed;}

從 retval = te->timeProc -> if 那段. 對于 id 打標為  AE_DELETED_EVENT_ID 標識輪循到的時候要洗掉. 

一旦 retval != AE_NOMORE 就再次修改這個timer Event 相關時間, 方便下次接著跑. 同樣我們抽一個例

子出來, 同樣核心也在 server.c 中 

[server.c]    /* Create the timer callback, this is our way to process many background     * operations incrementally, like clients timeout, eviction of unaccessed     * expired keys and so forth. */    if (aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) {        serverPanic("Can't create event loop timers.");        exit(1);    }[server.c]int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {...    return 1000/server.hz;}

整體看他這個 timer Event 很騷, 回傳毫秒時間后, 繼續注入進去, 繼續當回圈輪循定時器事件使用 

static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {    long cur_sec, cur_ms, when_sec, when_ms;    aeGetTime(&cur_sec, &cur_ms);    when_sec = cur_sec + milliseconds/1000;    when_ms = cur_ms + milliseconds%1000;    if (when_ms >= 1000) {        when_sec ++;        when_ms -= 1000;    }    *sec = when_sec;    *ms = when_ms;}

設計的思路挺巧妙的. 多數正常思路通過型別特殊處理, 或者特殊地方再次主動注冊. 

3. EventLoop 是怎么跑的?

EventLoop 奔跑思路很簡單, 一個地方輪循, 內部先跑 aeFileEvent, 再跑 aeTimeEvent

[ae.c]void aeMain(aeEventLoop *eventLoop) {    eventLoop->stop = 0;    while (!eventLoop->stop) {        if (eventLoop->beforesleep != NULL)            eventLoop->beforesleep(eventLoop);        aeProcessEvents(eventLoop, AE_ALL_EVENTS|AE_CALL_AFTER_SLEEP);    }}[server.c]int main(int argc, char **argv) {...    aeSetBeforeSleepProc(server.el,beforeSleep);    aeSetAfterSleepProc(server.el,afterSleep);    aeMain(server.el);    aeDeleteEventLoop(server.el);    return 0;}/* The End */

整體而言 redis ae 模型還是非常簡單, 處理的這些的事情完全是為 redis io 定制的. 夠用了. 

后續有機會我再大家分析 redis 中特定的 socket io 是怎么處理的. 

后記 - 為愛展望

? 錯誤是難免的, 歡迎有心同學指正和補充圖, 文字是干癟的 ~

 Here We Are Again - https://music.163.com/#/song?id=27876900

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/54984.html

標籤:C

上一篇:AD采集DAC芯片,連起來DAC不輸出低電平,是為什么?

下一篇:C語言歷史

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more