/**
* @file CM_MultiThread.c
* @brief 实现了线程操作的的封装
* @author GT-BU
* @date 2021.02.01
* @version V1.1
* @copyright TCT
* @par 修改日志
* <table>
* <tr><th>Date        <th>Version  <th>Author     <th>Description
* <tr><td>2017.12.20  <td>V1.0     <td>MSCP项目组 <td>创建初始版本
* <tr><td>2021.02.01  <td>V1.1     <td>GT-BU      <td>TSCP项目集成、更新
* </table>
*/
#include "CM_MultiThread.h"

#ifdef WIN32
/**
* @brief 创建线程
* @param thread 线程ID
* @param myfunc 线程执行函数
* @param threadName 线程名称
* @param stackSize 线程堆栈大小
* @param priority 线程优先级
* @param pargs 线程输入参数
* @return 执行结果
* - CM_TRUE 成功
* - CM_FALSE 失败
*/
CM_BOOL CM_Thread_Create(OUT CM_THREAD_T* thread, IN CM_THREAD_FUNC_T myfunc,IN const CM_CHAR* threadName,IN CM_INT32 stackSize,IN CM_INT32 priority,IN CM_Thread_Arg_Struct_T* pargs)
{
    /*- 变量初始化 */
    CM_THREAD_T tmpThread = 0u;   /*线程ID*/
    CM_BOOL rt = CM_FALSE;      /*函数返回值*/
    CM_UINT32 ThrAddr = 0u;  /*临时变量*/

    /*- 检查入口参数是否合法 */
    if ((stackSize >= 0)
        && ((priority == THREAD_PRIORITY_HIGHEST) || (priority == THREAD_PRIORITY_ABOVE_NORMAL)
            || (priority == THREAD_PRIORITY_NORMAL) || (priority == THREAD_PRIORITY_BELOW_NORMAL)
            || (priority == THREAD_PRIORITY_LOWEST) || (priority == THREAD_PRIORITY_IDLE)))
    {
        /*- 创建线程 */
        tmpThread = (CM_THREAD_T)_beginthreadex(NULL, (unsigned int)stackSize, myfunc, (void*)pargs, 0u, (unsigned int *)&ThrAddr);
        /*- 线程是否创建成功 */
        if (tmpThread > 0u)
        {
            /*- 设置线程优先级 */
            rt = SetThreadPriority((HANDLE)tmpThread, (int)priority);
            /*- 优先级是否设置成功 */
            if ((rt == CM_TRUE) && (thread != NULL))
            {
                /*- 输出线程ID */
                *thread = tmpThread;
            }
        }
    }
    /*- 返回执行结果 */
    return rt;
}

/**
* @brief 获取当前线程ID
* @return 线程ID
*/
CM_THREAD_T CM_Thread_Self(void)
{
    /*- 获取当前线程ID */
    CM_THREAD_T td = GetCurrentThreadId();
    /*- 返回线程ID */
    return td;
}
#endif