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