基于C++实现的线程休眠代码

2020-01-06 13:03:57丽君

本文实例讲述了基于C++实现的线程休眠代码,。具体方法如下:

linux平台示例如下:

 

  1. /*  File   : thread1.c 
  2. Author  : Mike  E-Mail  : Mike_Zhang@live.com 
  3. */  #include <stdio.h> 
  4. #include <pthread.h>  #include <time.h> 
  5. void m_threadSleep(int sec,int nsec)  { 
  6.   struct timespec sleepTime;    struct timespec returnTime; 
  7.   sleepTime.tv_sec = sec;    sleepTime.tv_nsec = nsec; 
  8.   nanosleep(&sleepTime, &returnTime);  } 
  9. void test1()  { 
  10.   m_threadSleep(1,0);    printf("I'm thread1 ...rn"); 
  11. }  void test2() 
  12. {    m_threadSleep(2,0); 
  13.   printf("I'm thread2 ...rn");  } 
  14. int main()  { 
  15.   pthread_t thread1,thread2;    void *result; 
  16.   time_t tbegin,tend;    tbegin = time(NULL); 
  17.   pthread_create(&thread1,NULL,(void*)&test1,NULL);    pthread_create(&thread2,NULL,(void*)&test2,NULL); 
  18.   pthread_join(thread1,&result);    pthread_join(thread2,&result); 
  19.   tend = time(NULL);    printf("%drn",tend-tbegin); 
  20.   return 0;  } 
?

编译代码如下:
 

  1. gcc thread1.c -o thread1 -lpthread