Thread sleep code (C ++)

Source: Internet
Author: User

Linux platform example:

 /*  
File: thread1.c
Author: Mike
E-mail: Mike_Zhang@live.com
*/
# Include <stdio. h>
# Include <pthread. h>
# Include <time. h>
Void M_threadsleep ( Int SEC, Int Nsec)
{
Struct Timespec sleeptime;
Struct Timespec returntime;
Sleeptime. TV _sec = sec;
Sleeptime. TV _nsec = nsec;
Nanosleep (& sleeptime, & returntime );
}
Void Test1 ()
{
M_threadsleep ( 1 , 0 );
Printf ( " I'm thread1... \ r \ n " );
}
Void Test2 ()
{
M_threadsleep (2 , 0 );
Printf ( " I'm thread2... \ r \ n " );
}
Int Main ()
{
Pthread_t thread1, thread2;
Void * Result;
Time_t tbegin, tend;
Tbegin = Time (null );
Pthread_create (& thread1, null ,( Void *) & Test1, null );
Pthread_create (& thread2, null ,( Void *) & Test2, null );
Pthread_join (thread1, & result );
Pthread_join (thread2, & result );
Tend = Time (null );
Printf ( " % D \ r \ n " , Tend-tbegin );
Return 0 ;
}

Compile:
GCC thread1.c-O thread1-lpthread

Example of boost library implementation:

 /* 
File: boost_thread1.cpp
Author: Mike
E-mail: Mike_Zhang@live.com
*/
# Include <boost/date_time/posix_time/posix_time.hpp>
# Include <boost/thread. HPP>
# Include <iostream>

Boost: xtime getsleeptime ( Int SEC, Int Nsec)
{
Boost: xtime T;
Boost: xtime_get (& T, boost: time_utc );
T. Sec + = sec;
T. nsec + = nsec;
Return T;
}
Void Test1 ()
{
Boost: this_thread: Sleep (getsleeptime ( 1 , 500 ));
STD: cout < " I'm thread1! " <STD: Endl;
}
Void Test2 ()
{
Boost: this_thread: Sleep (getsleeptime ( 3 ,500 ));
STD: cout < " I'm thread2! " <STD: Endl;
}

Int Main ( Int Argc, Char * Argv [])
{
Boost: thread thrd1 (& test1 );
Boost: thread thrd2 (& Test2 );
STD: time_t t_begin, t_end;
T_begin = Time (null );
Thrd1.join ();
Thrd2.join ();
T_end = Time (null );
STD: cout <t_end-t_begin <STD: Endl;
Return 0 ;
}

Compile command:
G ++ boost_thread1.cpp-O boost_thread1-lboost_thread-mt

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.