我目前正在研究一個安全的佇列結構。我在推送和彈出編輯佇列之前鎖定。當我完成它時解鎖它。現在我想讓執行緒在 pop-empty-queue 或 push-full-queue 時等待(此佇列已調整大小)。所以我在推送開始時檢查佇列是否已滿,并在彈出開始時使用相同的方式檢查佇列是否為空。如果是,那么我讓它等待pthread_cond_wait。為了讓它停止等待,我在推送結束時檢查佇列是否仍然為空,并在彈出結束時檢查佇列是否仍然滿。是不是空的還是滿的,然后我用pthread_cond_signal喚醒執行緒。我定義的結構就像
typedef struct node_t {
void* content;
struct node_t *next;
struct node_t *prev;
} node_t;
typedef struct queue_t {
node_t* head;
node_t* tail;
int size;
int count;
pthread_mutex_t mutex;
pthread_cond_t full; // To deal with the condition that the queue is full
pthread_cond_t empty; // To deal with the condition that the queue is empty
} queue_t;
我使用 lock 和 wait & send code 的方式是這樣的:
bool queue_push(queue_t *q, void *elem) {
if (q == NULL) {
return false;
}
while (q->count == q->size) {
pthread_cond_wait(&q->full, &q->mutex);
}
if (q->head == NULL) {
pthread_mutex_lock(&q->mutex);
// I skip the steps for adding a node to queue
if (q->count != 0) {
pthread_cond_signal(&q->empty);
}
pthread_mutex_unlock(&q->mutex);
return true;
} else {
pthread_mutex_lock(&q->mutex);
// I skip the steps for adding a node to queue
if (q->count != 0) {
pthread_cond_signal(&q->empty);
}
pthread_mutex_unlock(&q->mutex);
return true;
}
}
pop 的代碼有點相似。
bool queue_pop(queue_t *q, void **elem) {
if (q->count == 0) {
pthread_cond_wait(&q->empty, &q->mutex);
}
if (q->head == q->tail) {
pthread_mutex_lock(&q->mutex);
// I skip the steps for deleting a node to queue
if (q->count != q->size) {
pthread_cond_signal(&q->full);
}
pthread_mutex_unlock(&q->mutex);
return true;
} else {
pthread_mutex_lock(&q->mutex);
// I skip the steps for deleting a node to queue
if (q->count != q->size) {
pthread_cond_signal(&q->full);
}
pthread_mutex_unlock(&q->mutex);
return true;
}
}
現在,當我使用我的測驗用例對其進行測驗時,它永遠不會結束。但我確實解鎖并發送信號讓執行緒停止等待。有人可以幫我解決這個問題嗎?謝謝!
uj5u.com熱心網友回復:
如果您使用 c 只需使用 semaphore或者如果您使用 c 您可以使用POSIX semaphore,如果您想自己實作它,請檢查 spinlock。在任何情況下,您都可以使用自旋鎖實作阻塞器和釋放器,您可以創建一個中間件(鏈責任模式)并在所有呼叫中使用它。像這樣的東西。
void middleware (int (*func)(int, int)) {
block();
then();
release();
}
在 c 的情況下,您可以使用模板為所有方法實作一個中間件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/527242.html
標籤:C多线程队列
