--- title: 2021q1 quiz7 --- # 2021-04-06 `ParkerMactavish` ## 測驗一 --- ## 測驗二 ```c= static void enqueue(queue_t *q, int fd) { /* Construct new node */ node_t *node = malloc(sizeof(node_t)); node->fd = fd, node->next = NULL; pthread_mutex_lock(q->tail_lock); /* Add node to end of queue */ q->tail->next = node; q->tail = node; q->size++; /* 新增部分 */ if(q->size == 1) q->head = q->tail; /* 新增部分結束 */ /* 此部分是為了讓塞入第一個 node 的情況下讓 head 不會持續指向 dummy */ /* Wake any sleeping worker threads */ pthread_cond_signal(q->non_empty); pthread_mutex_unlock(q->tail_lock); } static void dequeue(queue_t *q, int *fd) { node_t *old_head; pthread_mutex_lock(q->head_lock); /* Wait until signaled that queue is non_empty. * Need while loop in case a new thread manages to steal the queue * element after the waiting thread is signaled, but before it can * re-acquire head_lock. */ /* 新增部分 */ while(pthread_cond_wait(q->non_empty, q->head_lock)); old_head = q->head; q->head = q->head->next; q->size--; *fd = old_head->fd; /* 新增部分結束 */ /* 等待 non_empty 被 signaled 後,便可以將可以使用的 head 指標取出,並將其複製至傳入的 fd 指標中 */ pthread_mutex_unlock(q->head_lock); free(old_head); } ``` 執行緒函式 greeter_routine 和 worker_routine 在上述網頁伺服器中,分別負責什麼功能? `greeter_routine` 負責取出連接請求,傳給 `worker_routine` 後由 `worker_routine` 進行來自 client 端資料的接收與回傳 client 端資料的傳送。 enqueue 和 dequeue 是單向鏈結串列 (singly-linked list) 所實作的佇列 (queue) 裡頭的基本操作,你如何驗證自己的實作能在並行環境正確無誤? ## 測驗三 ## 測驗四