我在獲取基本的雙線程安排方面有點麻煩。如何讓兩個pthread線程響應對方的等待和信號條件?
我正在一個「生產者」線程中從stdin
中讀取一大塊字節,並在第二個「消費者」線程中處理這些字節,一旦這些字節可用。一旦消耗了字節,消費者線程就回到休眠狀態,生產者線程再次運行。
我正在使用pthread_cond_wait()
和pthread_cond_signal()
讓兩個線程互相溝通數據是生成還是消耗。
下面是兩個線程的代碼:
void * produce_bytes(void *t_data)
{
pthread_data_t *d = (pthread_data_t *)t_data;
do {
pthread_mutex_lock(&d->input_lock);
d->n_bytes = fread(d->in_buf, sizeof(unsigned char), BUF_LENGTH_VALUE, stdin);
if (d->n_bytes > 0) {
fprintf(stdout, "PRODUCER ...signaling consumer...\n");
pthread_cond_signal(&d->input_cond);
fprintf(stdout, "PRODUCER ...consumer signaled...\n");
}
pthread_mutex_unlock(&d->input_lock);
} while (d->n_bytes > 0);
return NULL;
}
void * consume_bytes(void *t_data)
{
pthread_data_t *d = (pthread_data_t *)t_data;
pthread_mutex_lock(&d->input_lock);
while (d->n_bytes == 0)
pthread_cond_wait(&d->input_cond, &d->input_lock);
fprintf(stdout, "CONSUMER ...consuming chunk...\n");
d->n_bytes = 0;
fprintf(stdout, "CONSUMER ...chunk consumed...\n");
pthread_mutex_unlock(&d->input_lock);
}
的pthread_data_t
是我用它來跟蹤狀態的結構:
typedef struct {
pthread_mutex_t input_lock;
pthread_cond_t input_cond;
unsigned char in_buf[BUF_LENGTH_VALUE];
size_t n_bytes;
} pthread_data_t;
我配置我main()
函數變量;這裏是有關摘錄:
pthread_t producer_thread = NULL;
pthread_t consumer_thread = NULL;
pthread_data_t *thread_data = NULL;
thread_data = malloc(sizeof(pthread_data_t));
thread_data->n_bytes = 0;
pthread_mutex_init(&(thread_data->input_lock), NULL);
pthread_cond_init(&(thread_data->input_cond), NULL);
pthread_create(&producer_thread, NULL, produce_bytes, (void *) thread_data);
pthread_create(&consumer_thread, NULL, consume_bytes, (void *) thread_data);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
當我運行此,produce_bytes()
信號consume_bytes()
成功地在第一次循環,但在第二和後續的迭代,信號被髮送到consume_bytes()
,它永遠不會被聽到,所以消費者功能永遠不會被再次運行:
PRODUCER ...signaling consumer...
PRODUCER ...consumer signaled...
CONSUMER ...consuming chunk...
CONSUMER ...chunk consumed...
PRODUCER ...signaling consumer...
PRODUCER ...consumer signaled...
PRODUCER ...signaling consumer...
PRODUCER ...consumer signaled...
PRODUCER ...signaling consumer...
PRODUCER ...consumer signaled...
...
我使用的教程here至於是什麼,我試圖做的基礎。我做錯了什麼?
您的消費者的*外部循環*在哪裏?你有一個給你的製片人,但你的消費者似乎只關心首次到來。你的信號機制也可以清理一下。仔細看看你的消費線程,問自己在謂詞變爲真和'while循環中斷後會發生什麼。是否有*任何*現在會再次返回到謂詞循環? – WhozCraig
如果我嘗試''pthread_create'並在'produce_bytes()'函數內加入一個新的使用者線程,那麼一旦我有字節消耗,程序就會掛起。你能否添加一個答案來提出一種解決方法? –
是否有意添加任意數量的消費者?它有所作爲。無論如何,我幾乎已經爲你完成了單個/單個示例。 – WhozCraig