以下代码只是为演示多个线程使用互斥锁访问共享区,未考虑效率因素。
不过可以自行修改验证,2个线程比1个线程所花时间在用户态更短,在内核态较多,耗费时间就是在2个线程争用mutex锁上。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t c_lock; /* count lock */
long total_words = 0;
int main(int argc, char *argv[])
{
pthread_t tid1, tid2;
void *count_words(void*);
if( 3 != argc)
{
printf("Usage: %s file1 file2\n", argv[0]);
return 0;
}
pthread_create( &tid1, NULL, count_words, argv[1]);
pthread_create( &tid2, NULL, count_words, argv[2]);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("total_word=%ld\n", total_words);
return 0;
}
void *count_words(void *f)
{
char *filename = (char*)f;
FILE *fp;
int c, prevc='\0';
if(fp = fopen(filename, "r"))
{
while( (c=getc(fp)) != EOF)
{
if( !isalnum(c) && isalnum(prevc) )
{
pthread_mutex_lock( &c_lock);
total_words++;
pthread_mutex_unlock( &c_lock);
}
prevc = c;
}
fclose( fp );
}
else
{
perror(filename);
}
return NULL;
}
我们可以使用脚本先生成含有大量单词的文件,可参考《写指定数量的单词到文件》