2018年4月17日 星期二

[C][pthread] How to use pthread

#include <stdio.h>
#include <pthread.h>
#include <time.h>

static struct timespec start, now;

/** @return in ms */
static double time_diff(struct timespec t1, struct timespec t2)
{
    struct timespec diff;
    if (t2.tv_nsec - t1.tv_nsec < 0) {
        diff.tv_sec  = t2.tv_sec - t1.tv_sec - 1;
        diff.tv_nsec = t2.tv_nsec - t1.tv_nsec + 1000000000;
    } else {
        diff.tv_sec  = t2.tv_sec - t1.tv_sec;
        diff.tv_nsec = t2.tv_nsec - t1.tv_nsec;
    }
    return (diff.tv_sec * 1000.0 + diff.tv_nsec / 1000000.0);
}

void *happy()
{
 printf("Happy\n");
 clock_gettime(CLOCK_REALTIME, &start);
 do {
  clock_gettime(CLOCK_REALTIME, &now);
  printf("time elapse = %lf\n",time_diff(start, now));
 } while(time_diff(start, now) <= 10000 /* 10000 ms*/);
}

void main()
{
 pthread_t id;
 int ret;
 
 printf("main - Start\n");
 ret = pthread_create(&id, NULL, (void *) happy, NULL);
 if(ret!=0) {
  printf ("Create pthread error!\n");
 }
 while (1);
 printf("main - End\n");
}

Why need to “while (1)” at main function.
Using pthread, main function like brain, and pthread like second arm when it creates a new thread. So if brain(main function) died, pthread died as well.

0 意見:

張貼留言