coderplay
4/18/2013 - 7:17 AM

这段代码在2.6.18-164.el5xen会出现cpu 100%的情况

这段代码在2.6.18-164.el5xen会出现cpu 100%的情况

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>

#define NANOSECS_PER_SEC 1000000000

pthread_mutex_t lock;
pthread_cond_t  cond;

void _exec_and_wait(void* ignore) {
    static struct timeval now;
    static struct timespec time_to_wait;

    pthread_mutex_lock(&lock);
    while(1) {
        gettimeofday(&now, NULL);
        time_to_wait.tv_sec = now.tv_sec;
        time_to_wait.tv_nsec = now.tv_usec * 1000 + 999;
        //time_to_wait.tv_nsec = now.tv_usec * 1000 + 1000;
        if(time_to_wait.tv_nsec > NANOSECS_PER_SEC) {
           time_to_wait.tv_nsec -= NANOSECS_PER_SEC;
           ++time_to_wait.tv_sec;
        }
        pthread_cond_timedwait(&cond, &lock, &time_to_wait);
        // sleep(1);
        //printf("ok\n");
    }

    pthread_mutex_unlock(&lock);
}


/*
 *  main
 */
int main(int argc, char** argv)
{
    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&thread, &attr, _exec_and_wait, (void*)NULL );
    pthread_join(&thread, NULL);

    return (EXIT_SUCCESS);
}