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