skynet源碼學習 - 從全域隊列中彈出/壓入一個訊息佇列過程

來源:互聯網
上載者:User

標籤:skynet   skynet_mq   


學習雲風的skynet源碼,簡單記錄下。

void skynet_globalmq_push(struct message_queue * queue) {struct global_queue *q= Q;uint32_t tail = GP(__sync_fetch_and_add(&q->tail,1));// only one thread can set the slot (change q->queue[tail] from NULL to queue)if (!__sync_bool_compare_and_swap(&q->queue[tail], NULL, queue)) {// The queue may full seldom, save queue in list// 如果swap失敗說明queue[] 滿了,達到了64K個隊列,出現的幾率很小// 如果這樣的話,就把其儲存在Q的list中assert(queue->next == NULL);struct message_queue * last;do {last = q->list;queue->next = last;} while(!__sync_bool_compare_and_swap(&q->list, last, queue));return;}}// 結構體global_queue中的 head, tail 欄位分別控制著Q的取,存過程// GP呢可以看做是一個hash的過程,以此來確定其維護的queues的indexstruct message_queue * skynet_globalmq_pop() {struct global_queue *q = Q;uint32_t head =  q->head;if (head == q->tail) {// The queue is empty.return NULL;}uint32_t head_ptr = GP(head);struct message_queue * list = q->list;// 如果list非空,說明Q->queue曾經滿過,就把他們轉移回queue[]中,因為那裡速度更快if (list) {// If q->list is not empty, try to load it back to the queuestruct message_queue *newhead = list->next;if (__sync_bool_compare_and_swap(&q->list, list, newhead)) {// try load list only once, if success , push it back to the queue.list->next = NULL;skynet_globalmq_push(list);}}// 從頭取一個訊息佇列struct message_queue * mq = q->queue[head_ptr];if (mq == NULL) {// globalmq push not completereturn NULL;}// 取走一個訊息後自然要將index往後移動一個位置,並且剛那個position置為空白if (!__sync_bool_compare_and_swap(&q->head, head, head+1)) {return NULL;}// only one thread can get the slot (change q->queue[head_ptr] to NULL)if (!__sync_bool_compare_and_swap(&q->queue[head_ptr], mq, NULL)) {return NULL;}return mq;}


skynet源碼學習 - 從全域隊列中彈出/壓入一個訊息佇列過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.