其他分享
首页 > 其他分享> > thread互斥测试

thread互斥测试

作者:互联网

编译运行如下代码:

#include  <stdio.h>
#include  <stdlib.h>
#include  <pthread.h>
#include  <ctype.h>

struct arg_set {
	char *fname;
	int  count;
};

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;
struct arg_set args1, args2;	
int reports_in = 0;
int	total_words = 0;

if ( argc != 3 ){
	printf("usage: %s file1 file2\n", argv[0]);
	exit(1);
}

args1.fname = argv[1];
args1.count = 0;
pthread_create(&t1, NULL, count_words, (void *) &args1);

args2.fname = argv[2];
args2.count = 0;
pthread_create(&t2, NULL, count_words, (void *) &args2);

pthread_mutex_lock(&lock);//拿到互斥锁,进入临界区
while( reports_in < 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->fname);
	total_words += mailbox->count;
	if ( mailbox == &args1) 
		pthread_join(t1,NULL);//等待线程t1执行结束
	if ( mailbox == &args2) 
		pthread_join(t2,NULL);//等待线程t2执行结束
	mailbox = NULL;
	pthread_cond_signal(&flag);	//通知等待在条件变量上的线程
	reports_in++;
}
pthread_mutex_unlock(&lock);//释放互斥锁

printf("%7d: total words\n", total_words);
}
void *count_words(void *a)
{
struct arg_set *args = a;
FILE *fp;
int  c, prevc = '\0';

if ( (fp = fopen(args->fname, "r")) != NULL ){
	while( ( c = getc(fp)) != EOF ){
		if ( !isalnum(c) && isalnum(prevc) )
			args->count++;
		prevc = c;
	}
	fclose(fp);
} else 
	perror(args->fname);
printf("COUNT: waiting to get lock\n");
pthread_mutex_lock(&lock);//拿到互斥锁,进入临界区	
printf("COUNT: have lock, storing data\n");
if ( mailbox != NULL ){
	printf("COUNT: oops..mailbox not empty. wait for signal\n");
	pthread_cond_wait(&flag,&lock);
}
mailbox = args;			
printf("COUNT: raising flag\n");
pthread_cond_signal(&flag);	//通知等在条件变量上的线程
printf("COUNT: unlocking box\n");
pthread_mutex_unlock(&lock);	
return NULL;
}

源码截图:

编译运行过程以及结果:


此代码功能是互斥的查看两个文件中字符串的数量,第一个文件响获得锁,第二个就等待,等待第一个结束后再进行第二个文件的统计操作,最后输出总结果,总字符串数

标签:count,thread,lock,printf,mailbox,互斥,测试,pthread,NULL
来源: https://www.cnblogs.com/Werido-/p/15555150.html