pthread编程(3)——线程除法溢出

异常处理与信号机制在多线程编程中的应用
本文探讨了在多线程环境下如何使用信号机制来捕获并处理异常,通过设置自定义信号处理器,实现了在发生除零等错误时能够优雅地进行错误处理,避免了整个进程因异常而终止。
#include <pthread.h>
#include <signal.h>
#include <stdio.h>

#define ERROR printf("error @ %s line %d\n", __FILE__, __LINE__ );

void thread_cleanup( void *arg )
{
	printf( "cleanup is called\n" );
} 

void* threadfn_exception( void *arg )
{
	int i = 3;
	
	i /= 0;

	return NULL;
}

// FIXME
// endless output: catch a SIGFPE signal

void sigfpe_handler( int sig )
{
	printf( "catch a SIGFPE signal\n" );
}  

// exceptions in a thread may cause the whole process to be terminated!!

int main(int argc, char const *argv[])
{
	pthread_t thread;
	
	// if we set the handler to SIG_IGN/SIG_DFL, the process will be killed
	// signal does't work well if portability is taken into consideration, alternative is sigaction(3)
	signal( SIGFPE, sigfpe_handler );

	if( pthread_create( & thread, NULL, threadfn_exception, NULL ) )
	{
		ERROR;
		return -1;
	}
	if( pthread_join( thread, NULL ) )
	{
		ERROR;
		return -2;
	}
	printf("Done!\n");
	return 0;
}

转载于:https://my.oschina.net/iCode0410/blog/104568

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值