线程的创建,退出

由于在应用程序中,会不停的创建线程和删除线程,而这些线程都会使用同一个硬件资源,特此写了如下的一个demo,来测试这样操作线程是否会产生问题。

其中,线程创建部分:

static pthread_t pthread_Ch0_485_Process;
static void* Ch0_485_Process(void* arg);


void Ch0process_Create_Thread(void *ctx)
{
    printf("Begin to create RS485 ch0 Thread\n");
    if (pthread_create(&pthread_Ch0_485_Process, NULL, Ch0_485_Process, (void *)ctx) != 0)
    {
        printf("Fail to create Ch0 thread!\n");
    }

	printf("Success to create Ch0 thread!\n");
}

void* Ch0_485_Process(void* arg)
{
	bool bMaster;
	int rc;
	modbus_t *ctx;
	modbus_mapping_t *mb_mapping;
	MODBUS485_CONTEXT *pStr485Ctx;
	
	ctx = modbus_new_rtu(pRS485_Channel_Description[0], 115200, 'N', 8, 1);
	if (ctx == NULL)
	{
		printf("can't create modbus ctx\n");
	}

	printf("Success create modbus ctx\n");

	while(1)
	{
		usleep(1000); //此处就是线程退出的地方
	}
}

其中,usleep(1000) 函数,相当于在线程中个,加入了一个线程退出的地方。

另外,线程退出函数如下:

void Ch0process_Exit_Thread(void)
{
	void *status = NULL;

	if(pthread_cancel(pthread_Ch0_485_Process) != 0)
	{
		printf("CH0 Cancel failed\n");
		return;
	}

	if(pthread_join(pthread_Ch0_485_Process, &status) != 0) 
	{
		if(status != PTHREAD_CANCELED)
		{
			printf("thread exit failed\n");
			return;
		}
	}
	printf("CH0 exit success\n");
}

主函数调用如下:

#include "Ch0process.h"

int main(void)
{
	printf("Main thread\n");
	
	while(1)
	{
		sleep(1);
		Ch0process_Create_Thread(NULL);
		usleep(500);
		Ch0process_Exit_Thread();
	}
	
	return 0;
}

在linux板上,跑了大约20分钟,并未发现有什么问题。这样就能说明这样的思路暂时没问题。

Begin to create RS485 ch0 Thread
Success to create Ch0 thread!
Success create modbus ctx
CH0 exit success
Begin to create RS485 ch0 Thread
Success to create Ch0 thread!
Success create modbus ctx
CH0 exit success
Begin to create RS485 ch0 Thread
Success to create Ch0 thread!
Success create modbus ctx
CH0 exit success

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值