標籤: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源碼學習 - 從全域隊列中彈出/壓入一個訊息佇列過程