linux下线程通过signal通信实例

 1. linux系统中根据需求可选取不同的进程和线程间通信的方式,罗列如下:


using namespace std;
ServerMonitor* ServerMonitor::sServerMonitor=NULL;
#include <pthread.h>

#if 10
//调式linux下多线程间通信方式
int dataBuff[1000000];
int wAction=0,rAction=0;
int size=100;

pthread_cond_t buffIsNotEmpty;
pthread_cond_t buffIsNotFull;

//根据进程名获得获取进程数,判断当前服务进程是否正常运行
int ServerMonitor::GetPidNumber()
{
	int spaceNumber=0;
	int i;
	char pidBuffer[128];
	memset(pidBuffer,0,sizeof(pidBuffer));
	FILE *fp;
	if((fp=popen(PS_COMMAND,"r"))==NULL)
	{
		return 0;
	}
	fgets(pidBuffer,sizeof(pidBuffer),fp);
	
	for(i=0;i<strlen(pidBuffer);i++)
	{
		if(isspace(pidBuffer[i]))
		{
			spaceNumber++;
		}
		else
		{
			continue;
		}
	}
	printf("\r\n pidbuffer=%s, pid=%d  %d   %d\r\n",pidBuffer,spaceNumber,strlen(pidBuffer),sizeof(pidBuffer));
	return spaceNumber;
}
void *ServerMonitor::sMonitor(void *)
{
	printf("\r\n sMonitor \r\n");
	int x;
	while(1)
	{
		printf("\r\n sMonitor2 \r\n");
		pthread_mutex_lock(&lock);
		if(rAction==wAction)
		{
			printf("\r\n sMonitor3\r\n");
			pthread_cond_wait(&buffIsNotEmpty,&lock);
		}
			printf("\r\n sMonitor3\r\n");
			x=dataBuff[rAction++];
			if(rAction>=size)
			{
				rAction=0;
			}
			pthread_mutex_unlock(&lock);
			pthread_cond_signal(&buffIsNotFull);
		}
	return NULL;
}
//test signal sender
void *ServerMonitor::sExcute(void *)
{
#define TESTLEN 1000
	printf("\r\n sExcute \r\n");
	int i;
	for(i=0;i<=1000;i++)
	{
		pthread_mutex_lock(&lock);   //保证lock和unlock中间数据段为互斥操作,加锁
		if((wAction+1)%size==rAction)
		{
			pthread_cond_wait(&buffIsNotFull,&lock); //缓冲区未满,等待写端写入
		}
			dataBuff[wAction]=i;
			wAction++;
			if(wAction>=size)
			{
				wAction=0;
			}
			printf("\r\n write the data is %d \r\n",i);
			pthread_mutex_unlock(&lock);
		    pthread_cond_signal(&buffIsNotEmpty);
	}
	return NULL;
}
int ServerMonitor::CreateThreadPool(int pTmp)
{
	int pMTet=-1,pETet=-1;

	pthread_mutex_init(&lock,NULL);
	
	pthread_cond_init(&buffIsNotEmpty,NULL);
	pthread_cond_init(&buffIsNotFull,NULL);

	pETet=pthread_create(&sServerMonitor->sPool[EXECUTE_THD].id,NULL,sExcute,NULL);
	pMTet=pthread_create(&sServerMonitor->sPool[MONITOR_THD].id,NULL,sMonitor,NULL);
	if(pMTet!=0||pETet!=0) 
	 {
		 printf("\r\n CreateThreadPool falied \r\n");
			return -1;
	}
	pthread_join(sServerMonitor->sPool[EXECUTE_THD].id,NULL);
	pthread_join(sServerMonitor->sPool[MONITOR_THD].id,NULL);

}

int main()
{
	int initFlag=-1;
	memset(dataBuff,0,sizeof(dataBuff));

	ServerMonitor::GetInstance()->CreateThreadPool(pNumber);
	if(initFlag==-1) return -1;
	
	return 0;
}
2. 上面所述为使用C++实现的线程间生产者,消费者模式代码,头文件大家可以自己写,主要是一个单例模式。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值