Creating Threads

STM32CubeMX+FreeRTOS实战:3步搞定LED任务配置(附代码解析) 本文详细解析了如何使用STM32CubeMX图形化工具配置FreeRTOS实时操作系统,并创建LED闪烁任务。通过剖析MX_FREERTOS_Init()函数和CMSIS-RTOS封装层,深入理解任务创建、调度及osDelay()协作机制,帮助开发者从点击生成进阶到内核原理掌握,实现高效的多任务嵌入式开发。 阅读详情
http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx
 Creating Threads

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is the name of a function defined in the program code (for more information, see ThreadProc). This function takes a single parameter and returns a DWORD value. A process can have multiple threads simultaneously executing the same function.

The following is a simple example that demonstrates how to create a new thread that executes the locally defined function, MyThreadFunction.

The calling thread uses the WaitForMultipleObjects function to persist until all worker threads have terminated. The calling thread blocks while it is waiting; to continue processing, a calling thread would use WaitForSingleObject and wait for each worker thread to signal its wait object. Note that if you were to close the handle to a worker thread before it terminated, this does not terminate the worker thread. However, the handle will be unavailable for use in subsequent function calls.

#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define MAX_THREADS 3
#define BUF_SIZE 255

DWORD WINAPI MyThreadFunction( LPVOID lpParam );
void ErrorHandler(LPTSTR lpszFunction);

// Sample custom data structure for threads to use.
// This is passed by a void pointer so it can be any data type
// that can be passed using a single void pointer (LPVOID).
typedef struct MyData {
    int val1;
    int val2;
} MYDATA, *PMYDATA;

int _tmain()
{
    PMYDATA pDataArray[MAX_THREADS];
    DWORD   dwThreadIdArray[MAX_THREADS];
    HANDLE  hThreadArray[MAX_THREADS]; 

    // Create MAX_THREADS worker threads.

    for( int i=0; i<MAX_THREADS; i++ )
    {
        // Allocate memory for thread data.

        pDataArray[i] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                sizeof(MYDATA));

        if( pDataArray[i] == NULL )
        {
           // If the array allocation fails, the system is out of memory
           // so there is no point in trying to print an error message.
           // Just terminate execution.
            ExitProcess(2);
        }

        // Generate unique data for each thread to work with.

        pDataArray[i]->val1 = i;
        pDataArray[i]->val2 = i+100;

        // Create the thread to begin execution on its own.

        hThreadArray[i] = CreateThread( 
            NULL,                   // default security attributes
            0,                      // use default stack size  
            MyThreadFunction,       // thread function name
            pDataArray[i],          // argument to thread function 
            0,                      // use default creation flags 
            &dwThreadIdArray[i]);   // returns the thread identifier 


        // Check the return value for success.
        // If CreateThread fails, terminate execution. 
        // This will automatically clean up threads and memory. 

        if (hThreadArray[i] == NULL) 
        {
           ErrorHandler(TEXT("CreateThread"));
           ExitProcess(3);
        }
    } // End of main thread creation loop.

    // Wait until all threads have terminated.

    WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);

    // Close all thread handles and free memory allocations.

    for(int i=0; i<MAX_THREADS; i++)
    {
        CloseHandle(hThreadArray[i]);
        if(pDataArray[i] != NULL)
        {
            HeapFree(GetProcessHeap(), 0, pDataArray[i]);
            pDataArray[i] = NULL;    // Ensure address is not reused.
        }
    }

    return 0;
}

DWORD WINAPI MyThreadFunction( LPVOID lpParam ) 
{ 
    HANDLE hStdout;
    PMYDATA pDataArray;

    TCHAR msgBuf[BUF_SIZE];
    size_t cchStringSize;
    DWORD dwChars;

    // Make sure there is a console to receive output results. 

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if( hStdout == INVALID_HANDLE_VALUE )
        return 1;

    // Cast the parameter to the correct data type.
    // The pointer is known to be valid because 
    // it was checked for NULL before the thread was created.
 
    pDataArray = (PMYDATA)lpParam;

    // Print the parameter values using thread-safe functions.

    StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d/n"), 
        pDataArray->val1, pDataArray->val2); 
    StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
    WriteConsole(hStdout, msgBuf, (DWORD)cchStringSize, &dwChars, NULL);

    return 0; 
} 

void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code.

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message.

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    // Free the error-handling buffer allocations.

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

The MyThreadFunction function avoids the use of the C run-time library (CRT), as many of its functions are not thread-safe, particularly if you are not using the multithreaded CRT. If you would like to use the CRT in a ThreadProc function, use the _beginthreadex function instead.

It is risky to pass the address of a local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass a pointer to dynamically allocated memory or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads.

The creating thread can use the arguments to CreateThread to specify the following:

  • The security attributes for the handle to the new thread. These security attributes include an inheritance flag that determines whether the handle can be inherited by child processes. The security attributes also include a security descriptor, which the system uses to perform access checks on all subsequent uses of the thread's handle before access is granted.
  • The initial stack size of the new thread. The thread's stack is allocated automatically in the memory space of the process; the system increases the stack as needed and frees it when the thread terminates. For more information, see Thread Stack Size.
  • A creation flag that enables you to create the thread in a suspended state. When suspended, the thread does not run until the ResumeThread function is called.

You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.

CloudCompare点云滤波实战:三种植被去除技术的对比与应用 本文详细对比了CloudCompare中三种植被去除技术(低通滤波、CSF滤波和坡度法)的实战应用与效果。通过具体案例和参数优化建议,帮助用户根据地形特征选择最佳滤波方法,提升点云数据处理精度和效率,特别适用于复杂场景下的植被去除需求。 阅读详情

相关推荐

DRV2605L触觉驱动芯片实战指南:从自动校准到音频转触觉应用

触觉反馈技术是现代人机交互的核心组成部分,它通过精确控制振动马达来模拟物理触感,广泛应用于智能手机、游戏手柄和汽车触摸屏等领域。其原理在于将电信号转化为机械振动,关键在于如何高效、精准地驱动不同类型的马达(如ERM和LRA)。这项技术的核心价值在于提升交互的真实感和沉浸感。在工程实践中,集成驱动芯片如DRV2605L通过内置智能反馈引擎和自动校准功能,解决了传统驱动方式响应慢、效果不一致的难题。它特别适用于需要高质量触觉反馈的应用场景,例如消费电子、游戏外设和车载信息娱乐系统。其中,自动校准能自适应优化驱动

weixin_42631411的博客 344

Android如何结束并重启线程?

相信开发过游戏的人都认识SurfaceView的双线程双缓冲机制。但一旦当前Activity退出到Home,再回到Activity便会报错:Thread already started.             寻找过网上的解决方法,一个是退出到Home时触发surfaceDestroyed()事件,令thread stop。回到Activity时触发surfaceCreated事件令threa

helwens的专栏 4352

CCS8.1 导入CCS3.3工程方法

    CCS3.3作为开发人员使用最广开发工具,研究人员手上存在不少该版本的建立的程序版本,然而随着TI公司推出高级版本的CCS平台,在新的平台上集成了更加丰富的功能和优点。利用新版本的平台在开发和编译旧版本工程上可以节省大量时间和精力。在使用新版本开发3.3版本工程时,首要解决的就是加载3.3的工程文件,现将加载过程记录如下: 第一步:Project-&gt;Import Legacy CC...

1万+

Creating Threads - 创建线程

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is

uag 的博客 867

从零开始的机械臂yolov5抓取gazebo仿真(一)

本文介绍了如何将机械臂模型导出为URDF

qq_48427527的博客 1万+

UG/NX二次开发实战:用Python脚本批量更新100个零件参数,解放你的双手

本文详细介绍了如何利用NXOpen Python API进行UG/NX二次开发,实现批量更新100个零件参数的自动化流程。通过环境配置、框架设计、核心代码实现及性能优化,帮助工程师高效完成参数化设计任务,显著提升工作效率。

weixin_28694169的博客 282

c3po异常:Creating emergency threads for unassigned pending tasks!

转载于:http://www.blogjava.net/liuyimx/articles/296849.html<br />这是我换了数据库以后报的错误:<br /> <br /> 原因:网上多是说c3p0 bug引起的我的数据库oracle 10.2.0.1,oracle14.jar也是10.2.0.1版本,我做了两个修改这个错误就没有了,具体原因还不明,先解决了再说。一.修改数据库方言为oracle.jdbc.driver.OracleDriver(原来为oracle.jdbc.OracleDriver

zgmzyr的专栏 2468

python气象数据可视化学习笔记8——利用matplotlib和ERA5数据绘制时间-高度气象综合廓线图

利用matplotlib和ERA5数据绘制时间-高度气象综合廓线图

qiuylulu的博客 8074

Windows Creating Threads

TheCreateThreadfunction creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is th...

lixiaoguang20的博客 406

YOLOv8独家原创改进:原创自研 | 创新自研CPMS注意力,多尺度通道注意力具+多尺度深度可分离卷积空间注意力,全面升级CBAM

自研CPMS,多尺度通道注意力具+多尺度深度可分离卷积空间注意力,全面升级CBAM

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 3808

(汇总篇)语义SLAM相关开源方案| 全球优秀作者与实验室 | SLAM学习资料整理

SLAM 与深度学习相结合的工作当前主要体现在两个方面,一方面是将语义信息参与到建图、位姿估计等环节中,另一方面是端到端地完成 SLAM。针对建图的工作一方面是利用几何信息进行稠密重建,另一方面很多工作利用语义信息达到了很好的语义重建效果,三维重建、SFM。动态 SLAM 也是一个很值得研究的话题,这里不太好分类,很多工作用到了语义信息或者用来三维重建,收集的方案相对较少。优化可能是 SLAM 中最难的一部分了吧 +_+ ,一般都是直接用现成的因子图、图优化方案,要创新可不容易。

熊猫小妖的AI世界 7876

Creating threads in Java

There are in general two ways to create and start a new thread in Java. 1. extend the Thread class and override the run() method public class MyThread extends Thread{ @Override public void r

Andrew's Blog 952

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Creating and Starting Threads

Creating and Starting Threads(创建和运行线程) 通过多线程基本概念的介绍,我们知道线程是通过传入一个ThreadStart的委托给Thread类的构造函数创建的。下面是ThreadStart类的定义。 1: public delegate void ThreadStart(); 通过调用线程的Start方法使线程运行...

weixin_30514745的博客 104

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

creating emergency threads for unassigned pending tasks

参考这个:http://www.blogjava.net/liuyimx/archive/2013/05/03/296849.html 错误出现原因是数据库配置错误,但是一开始没有打印出数据库错误而是显示com.mchange.v2.async.ThreadPoolAsynchronous。。。-- APPARENT DEADLOCK!!! Complete Status: 后来过一阵

xinglu31的专栏 1737

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

WebLogic Stuck Threads: Creating, Understanding and Dealing with them

src: http://www.munzandmore.com/2012/ora/weblogic-stuck-threads-howto  Using the time off during the bank holidays over Easter I spent some time coding and looking into more unknown details of We

编程岁月 1448

Creating Concurrency with Threads

把任务放到线程中执行的时候,执行的那段代码要放在autoreleasepool中。

Smiling8866的博客 414

c3p0 apparent deadlock / creating emergency threads

Code: 2005-09-06@06:29:12.383 WARN [Timer-0] - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@130b13c -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending t...

子墨 254

APPARENT DEADLOCK Creating emergency threads for unassigned pending tasks

在迁移CDH集群的元数据库后,重新启动集群失败,报APPARENT DEADLOCK!!! 错误

QiwzDeBLOG的博客 3413

APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks

  最近orcale数据只有一台可以服务,导致hibernate 连接数据库每个13分钟就会报“APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks”的错误.原因是 hibernate 使用c3p0连接orcale数据后不会释放 , c3p0的最大连接数为100,但显然c3p0有Bug,导致数...

yqling2008 1410

APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!

每天上午的大好时光都被傻逼问题困扰,耽误时间。 因为要部署,昨天改了下mysql url 的连接 ip,后面改回来了,但是就一直报错。貌似是连不上,郁闷的一笔。错误如下:  解决方法就是:我先的是主机名改为ip后,ok了,后面我又改回主机名,又没问题了。中间只是用客户端测试了下能否连接。what a funcking day! [Timer-0] WARN  com.mchange.v2.as

laokaizzz的专栏 2288

Creating a Manager for Multiple Threads_翻译

The previous lesson showed how to define a task that executes on a separate thread. If you only want to run the task once, this may be all you need. If you want to run a task repeatedly on diffe...

dichen3940的博客 130

解决 APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tas

(转)解决 APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tas原文来源:http://billyshao.iteye.com/blog/1831840最近把项目迁移到weblogic下运行,结果一直报错,报错信息:APPARENT DEADLOCK!!! Creating emergency thre

abcyyjjkk的博客 1万+
上一篇: 其他公司的笔试题6
下一篇: 推荐一些免费的网盘给你
skyremember
博客等级 码龄20年 205粉丝 484原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址