Created
October 28, 2013 12:54
-
-
Save foxish/7196333 to your computer and use it in GitHub Desktop.
Context switches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
#include <sys/time.h> | |
#include <inttypes.h> | |
#include <semaphore.h> | |
pthread_cond_t CONDITION; | |
pthread_mutex_t LOCK; | |
uint32_t COUNTER; | |
pthread_t t1, t2; | |
sem_t START; | |
void* exec_thread(void* unused){ | |
sem_wait(&START); | |
printf("Executing thread\n"); | |
if (COUNTER > 0) { | |
pthread_cond_signal(&CONDITION); | |
} | |
for (;;) { | |
COUNTER++; | |
pthread_cond_wait(&CONDITION, &LOCK); | |
pthread_cond_signal(&CONDITION); | |
} | |
} | |
int64_t timeInMS(){ | |
struct timeval t; | |
gettimeofday(&t, NULL); | |
return ( | |
(int64_t)t.tv_sec * 1000 + | |
(int64_t)t.tv_usec / 1000 | |
); | |
} | |
int main(){ | |
int64_t start, end; | |
//init | |
pthread_mutex_init(&LOCK, NULL); | |
pthread_cond_init(&CONDITION, NULL); | |
//create pthread | |
pthread_create(&t1, NULL, exec_thread, NULL); | |
pthread_create(&t2, NULL, exec_thread, NULL); | |
//detach as we won't call join() | |
pthread_detach(t1); | |
pthread_detach(t2); | |
//number of context switches | |
start = timeInMS(); | |
sem_init(&START, 0, 2); | |
pthread_mutex_unlock(&LOCK); | |
sleep(1); | |
pthread_mutex_lock(&LOCK); | |
end = timeInMS(); | |
printf("%f\n", COUNTER/((double)(end-start)/1000.0)); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment