pthread编程(2)——pthread_cleanup

使用pthread_cleanup处理线程取消
本文介绍了一个使用pthread_cleanup_push和pthread_cleanup_pop处理线程取消的C语言示例。通过定义thread_cleanup函数来演示如何在线程被取消时进行清理工作。在main函数中创建并取消线程,展示如何确保线程完成清理过程。
// 2013年 01月 24日 星期四 18:31:36

#include <pthread.h>
#include <stdio.h>


// pthread_cleanup_push and pthread_cleanup_pop should be called in pairs at the same lexical nesting level
// they are implemented with '{' '}'

// pthread_cleanup_pop with non-zero argument/pthread_cancel/pthread_exit 
// will cause the remained handler to be popped and executed

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

void thread_cleanup( void *arg )
{
	// __func__ can be used instead
	printf("%s is called\n", __FUNCTION__ );
}

void* threadfn( void *data )
{
	pthread_cleanup_push( thread_cleanup, NULL );

	sleep( 20 );

	pthread_cleanup_pop( 1 );
}

int main(int argc, char const *argv[])
{
	pthread_t thread;

	if ( pthread_create( &thread, NULL, threadfn, NULL) )
	{
		ERROR;
		return -1;
	}

	sleep( 1 );

	// cancel the thread before it exits
	if( pthread_cancel( thread ) )
	{
		ERROR;
		return -1;
	}

	// wait for thread to complete it's cleanup
	if( pthread_join( thread, NULL ) )
	{
		ERROR;
		return -1;
	}

	printf("Done!\n");

	return 0;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值