码迷,mamicode.com
首页 > 其他好文 > 详细

信号量与互斥锁性能对比

时间:2015-02-16 11:44:03      阅读:704      评论:0      收藏:0      [点我收藏+]

标签:

/*************************************************************************
    > File Name: semaphore.c
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com 
    > Created Time: Sun 15 Feb 2015 09:37:23 AM WST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <time.h>

uint n;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t sem_id;
time_t start, finish;
void *add_unlock(void *arg) {
	uint i;
	start = clock();
	for(i = 0;i < 1e6;i++) n++;
	finish = clock();

	return NULL;
}
void *add_mutex(void *arg) {
	start = clock();
	pthread_mutex_lock(&mutex);
	while(n < 1e6) n++;
	pthread_mutex_unlock(&mutex);
	finish = clock();

	return NULL;
}
void *add_sem(void *arg) {
	start = clock();
	sem_wait(&sem_id);
	while(n < 1e6) n++;
	sem_post(&sem_id);
	finish = clock();

	return NULL;
}

int main() {
	/*
	 * single thread
	 * */
//	add_unlock(NULL);
//	double elapse = (double)(finish - start) / CLOCKS_PER_SEC;
//	printf("elapse time = %lf\n", elapse);   // 0.01s

	/*
	 * 16 threads synchronize by mutex lock
	 * */
/*	pthread_t thread_ids[16];
	int i;
	for(i = 0;i < 16;i++) {
		pthread_create(&thread_ids[i], NULL, add_mutex, NULL);
	}
	for(i = 0;i < 16;i++) {
		pthread_join(thread_ids[i], NULL);
	}
	double elapse = (double)(finish - start) / CLOCKS_PER_SEC;
	printf("elapse time = %lf\n", elapse);   // 0.03s
*/
	/*
	 * 16 threads synchronize by semaphore
	 * */
/*	sem_init(&sem_id, 0, 1);
	pthread_t thread_ids[16];
	int i;
	for(i = 0;i < 16;i++) {
		pthread_create(&thread_ids[i], NULL, add_sem, NULL);
	}
	for(i = 0;i < 16;i++) {
		pthread_join(thread_ids[i], NULL);
	}
	double elapse = (double)(finish - start) / CLOCKS_PER_SEC;
	printf("elapse time = %lf\n", elapse);	// 0.016s
*/


	return 0;
}

信号量与互斥锁性能对比

标签:

原文地址:http://blog.csdn.net/wangzhicheng1983/article/details/43850891

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!