80 lines
1.7 KiB
C++
80 lines
1.7 KiB
C++
|
|
#include <iostream> // std::cout
|
|
#include <thread> // std::thread
|
|
#include <mutex> // std::mutex, std::unique_lock
|
|
#include <condition_variable> // std::condition_variable
|
|
#include <sys/time.h> // time in nano-sec
|
|
#include <unistd.h> // usleep
|
|
|
|
#define nTh 5
|
|
|
|
std::mutex mtx[nTh];
|
|
std::condition_variable cv;
|
|
bool ready = false;
|
|
|
|
timespec ts[nTh];
|
|
|
|
void print_id(int id) {
|
|
std::unique_lock<std::mutex> lck(mtx[id]);
|
|
while (!ready ){
|
|
printf("waiting for unlock %d\n", id);
|
|
cv.wait(lck);
|
|
}
|
|
cv.notify_all();
|
|
|
|
clock_gettime(CLOCK_REALTIME, &ts[id]);
|
|
printf("----thread %d ready. %ld ns\n", id, ts[id].tv_nsec);
|
|
|
|
usleep(2000*2000);
|
|
|
|
printf("thread %d finished.\n", id);
|
|
|
|
}
|
|
|
|
void go() {
|
|
ready = true;
|
|
cv.notify_all();
|
|
}
|
|
|
|
int main(){
|
|
|
|
std::thread threads[nTh];
|
|
|
|
for (int i = 0; i < nTh; ++i){
|
|
threads[i] = std::thread(print_id, i);
|
|
}
|
|
|
|
printf("%d threads ready to race...\n", nTh);
|
|
|
|
usleep(1000*1000);
|
|
|
|
go(); // go!
|
|
|
|
for (auto& th : threads) th.join();
|
|
|
|
printf("=========== finsihed.\n");
|
|
|
|
long avg = 0;
|
|
for( int i =0; i < nTh ; i++) avg += ts[i].tv_nsec;
|
|
avg = avg/nTh;
|
|
|
|
long min , max;
|
|
|
|
for( int i =0; i < nTh; i++) {
|
|
if( i == 0 ){
|
|
min = ts[i].tv_nsec;
|
|
max = ts[i].tv_nsec;
|
|
continue;
|
|
}
|
|
if( min > ts[i].tv_nsec) min = ts[i].tv_nsec;
|
|
if( max < ts[i].tv_nsec) max = ts[i].tv_nsec;
|
|
}
|
|
|
|
printf(" avg : %ld\n", avg);
|
|
printf(" min : %ld, %ld\n", min, avg - min);
|
|
printf(" max : %ld, %ld\n", max, max - avg);
|
|
printf(" diff : %ld\n", max-min);
|
|
|
|
return 0;
|
|
}
|