Created
November 3, 2015 14:24
-
-
Save gnitnaw/6129098182bfd1f7c607 to your computer and use it in GitHub Desktop.
Example of pthread_cond_wait
This file contains 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 <string.h> | |
#include <pthread.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <sys/mman.h> | |
#define NLOOP 30 | |
int global_thread = 0; | |
pthread_mutex_t mutex; | |
pthread_cond_t cond[5]; | |
void _usleep(int micro) | |
{ | |
struct timespec req = {0}; | |
req.tv_sec = 0; | |
req.tv_nsec = micro * 1000L; | |
nanosleep(&req, (struct timespec *)NULL); | |
} | |
void* Thread(void* x) { | |
int i; | |
int *X = (int*) x; | |
for (i=0; i<5; ++i) { | |
pthread_mutex_lock(&mutex); | |
printf("This thread should sleep %d000 microsecond\n", *X); | |
while (global_thread != *X) { | |
printf("Thread %d wait\n", *X); | |
pthread_cond_wait(&cond[*X], &mutex); | |
} | |
printf("Thread %d Enter!\n", *X); | |
global_thread = 0; | |
pthread_mutex_unlock(&mutex); | |
_usleep(*X * 1000); | |
} | |
printf("Thread %d Exit! \n", *X); | |
pthread_exit(NULL); | |
} | |
int main(void) { | |
struct sched_param sp; | |
memset(&sp, 0, sizeof(sp)); | |
sp.sched_priority = sched_get_priority_max(SCHED_FIFO); | |
//sp.sched_priority = 49; | |
sched_setscheduler(0, SCHED_FIFO, &sp); | |
mlockall(MCL_CURRENT | MCL_FUTURE); | |
int i; | |
int a=1, b=2, c=3, d=4; | |
float dt[NLOOP]; | |
struct timespec tp1, tp2; | |
unsigned long startTime, procesTime; | |
pthread_t pid_1, pid_2, pid_3, pid_4; | |
for (i=0; i<5; ++i) { | |
pthread_cond_init(&cond[i],NULL); | |
// pthread_mutex_init(&mutex[i],NULL); | |
} | |
pthread_mutex_init(&mutex,NULL); | |
pthread_create(&pid_1,NULL,Thread, (void*)&a); | |
pthread_create(&pid_2,NULL,Thread, (void*)&b); | |
pthread_create(&pid_3,NULL,Thread, (void*)&c); | |
pthread_create(&pid_4,NULL,Thread, (void*)&d); | |
sleep(5); | |
puts("============================================"); | |
clock_gettime(CLOCK_REALTIME, &tp1); | |
startTime = tp1.tv_sec*1000000000 + tp1.tv_nsec; | |
for (i=0; i<NLOOP; ++i) { | |
puts(""); | |
printf("LOOP %d\n", i); | |
global_thread = i%5; | |
if (global_thread <5) pthread_cond_signal(&cond[global_thread]); | |
_usleep(5000); | |
clock_gettime(CLOCK_REALTIME, &tp2); | |
startTime = tp1.tv_sec*1000000000 + tp1.tv_nsec; | |
procesTime = tp2.tv_sec*1000000000 + tp2.tv_nsec - startTime; | |
dt[i] = (float)procesTime /1000.0; | |
tp1 = tp2; | |
} | |
pthread_join(pid_1, NULL); | |
pthread_join(pid_2, NULL); | |
pthread_join(pid_3, NULL); | |
pthread_join(pid_4, NULL); | |
for (i=0; i<NLOOP; ++i) { | |
printf("%d, %f\n", i, dt[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment