两个线程按特定时间顺序交替执行

1、用到setitimer()函数,设定定时器

2、boost库用于创建两个线程

3、signal()用于将定时信号与响应函数绑定

源码如下:

#include<iostream>
#include<csignal>
#include<sys/time.h>
#include<boost/thread/thread.hpp>
using namespace std;

bool en_transmit=false,en_receive=false;

void transmit(void){
		cout<<"Transmit called..."<<endl;
		while(en_transmit){cout<<"";}
		cout<<"Finished Send..."<<endl<<endl;
		return;
}

void receive(void){
		cout<<"Receive called..."<<endl;
		while(en_receive){cout<<"";}
		cout<<"Finished Recv..."<<endl<<endl;
		return;
}

bool period=false;
void sigroutine(int signo){
		pthread_t send,recv;
		cout<<signo<<endl;
		boost::thread_group threads;
		switch(signo){
				case SIGALRM:
						en_receive=false;
						en_transmit=true;
						threads.create_thread(&transmit);
						break;
				case SIGVTALRM:
						en_transmit=false;
						en_receive=true;
						threads.create_thread(&receive);
						break;
		}
		return;
}

int main(){
		struct time{
				int sec;
				int usec;
		};

		struct time period;
		period.sec=5;
		period.usec=0;
		struct itimerval value,ovalue,value2;

		signal(SIGALRM,sigroutine);
		signal(SIGVTALRM,sigroutine);

		value.it_value.tv_sec=1;
		value.it_value.tv_usec=0;
		value.it_interval.tv_sec=period.sec;
		value.it_interval.tv_usec=period.usec;
		setitimer(ITIMER_REAL,&value,&ovalue);

		value2.it_value.tv_sec=2;
		value2.it_value.tv_usec=0;
		value2.it_interval.tv_sec=period.sec;
		value2.it_interval.tv_usec=period.usec;
		setitimer(ITIMER_VIRTUAL,&value2,&ovalue);

		while(1){
				pause();
		}

		return 0;
}


编译:g++ thread.cpp -o thread -lboost_thread

运行效果如下:

两个线程按特定时间顺序交替执行_第1张图片

你可能感兴趣的:(C++,线程,定时器,boost)