信号量与互斥锁性能对比

/*************************************************************************
    > 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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值