由于在应用程序中,会不停的创建线程和删除线程,而这些线程都会使用同一个硬件资源,特此写了如下的一个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