下面的程式碼出自《Unix/Linux程式設計實作教學》,作用是用兩個執行緒分別統計兩個檔案的單字的數目,並在主執行緒中計算總數。下面是運行截圖:
#但是看了半天還是難以理解下面程式碼中的加鎖、解鎖以及條件變數。
我想問:
主執行緒中呼叫pthread_cond_wait
時會釋放互斥鎖,然後掛起主執行緒,並等待條件變數的變化,當其他執行緒呼叫pthread_cond_signal
時,如果互斥鎖是被鎖住的,那麼主線程中的pthread_cond_wait
會等互斥待鎖被解鎖後,然後再給互斥鎖上鎖後再返回嗎?
如果正如1中的描述那樣的話,pthread_cond_wait
收到了pthread_cond_signal
發來的訊號,但是未鎖定互斥鎖之前,又被其他執行緒搶了先,鎖住了互斥鎖,那不是pthread_cond_wait
還得掛起等待互斥鎖被解鎖?
如果可以的話,希望能幫忙釐清這個程式的執行流程。
萬分感謝。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
struct arg_set { /* two values int one arg */
char *filename; /* file to examine */
int count; /* number of words */
int code;
};
struct arg_set *mailbox = NULL;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
void *count_words(void *);
int main(int argc, char *argv[])
{
pthread_t t1, t2; /* two threads */
struct arg_set args1, args2; /* two argsets */
int reports_int = 0;
int total_words = 0;
if (argc != 3) {
fprintf(stderr, "usage: %s file1 file2", argv[0]);
exit(1);
}
pthread_mutex_lock(&lock);
args1.filename = argv[1];
args1.count = 0;
args1.code = 1;
pthread_create(&t1, NULL, count_words, (void *)&args1);
args2.filename = argv[2];
args2.count = 0;
args2.code = 2;
pthread_create(&t2, NULL, count_words, (void *)&args2);
while (reports_int < 2) { // 等待其他线程结束
printf("MAIN: waiting for flag to go up\n");
pthread_cond_wait(&flag, &lock);
printf("MAIN: Wow! flag was raised, I have the lock\n");
printf("%7d: %s\n", mailbox->count, mailbox->filename);
total_words += mailbox->count;
if (mailbox == &args1)
pthread_join(t1, NULL);
if (mailbox == &args2)
pthread_join(t2, NULL);
mailbox = NULL;
pthread_cond_signal(&flag);
reports_int++;
}
printf("%7d: total words\n", total_words);
return 0;
}
void *count_words(void *a)
{
struct arg_set *args = a;
FILE *fp;
int c, prevc = 'rrreee';
if ((fp = fopen(args->filename, "r")) != NULL) { // 统计单词个数
while ((c = getc(fp)) != EOF) {
if (!isalnum(c) && isalnum(prevc))
args->count++;
prevc = c;
}
fclose(fp);
} else
perror(args->filename);
printf("COUNT %d: waiting to get lock\n", args->code);
pthread_mutex_lock(&lock);
printf("COUNT %d: have lock, storing data\n", args->code);
if (mailbox != NULL)
pthread_cond_wait(&flag, &lock);
mailbox = args;
printf("COUNT %d: raising flag\n", args->code);
pthread_cond_signal(&flag);
printf("COUNT %d: unlocking box\n", args->code);
pthread_mutex_unlock(&lock);
return NULL;
}
沒什麼複雜的,主執行緒取得鎖定後,進入休眠,等一個訊號來喚醒它。
pthread_cond_signal
就是這個訊號這種鎖與別的鎖有點不同,其它類型的鎖是:線程申請鎖,沒有得到鎖,線程就進入休眠,等待。
這種鎖是有鎖就休眠,等別的線叫醒它。