什么是线程?如何在win32应用程序中创建线程?

时间:2009-12-24 12:13:24

标签: winapi

什么是线程?如何在win32应用程序中创建线程?

5 个答案:

答案 0 :(得分:8)

线程是一个轻量级的过程。线程可以松散地定义为单独的执行流,它与可能发生的所有其他事件同时发生并独立发生。线程就像一个经典程序,它从A点开始执行,直到它到达B点。它没有事件循环。线程独立于计算机中发生的任何其他操作。没有线程,整个程序可以由一个CPU密集型任务或一个无限循环(有意或无意)来保持。对于线程,其他不会卡在循环中的任务可以继续处理,而无需等待卡住的任务完成。 请仔细阅读此链接以获取更多详细信息及其与流程的比较。

  

http://en.wikipedia.org/wiki/Thread_(computer_science)

创建线程非常容易,例如通过这个....

这是一个创建线程的例子,即ThreadFun1

#include<windows.h>
#include<stdio.h>
#include<conio.h>

void __stdcall ThreadFun1()
{
    printf("Hi This is my first thread.\n");
}
void main()
{
    printf("Entered In Main\n");
    HANDLE hThread;
    DWORD threadID;
    hThread = CreateThread(NULL, // security attributes ( default if NULL )
                            0, // stack SIZE default if 0
                            ThreadFun1, // Start Address
                            NULL, // input data
                            0, // creational flag ( start if  0 )
                            &threadID); // thread ID
    printf("Other business in Main\n"); 
    printf("Main is exiting\n");
    CloseHandle(hThread);
    getch();
}

答案 1 :(得分:3)

如果您正在编写C / C ++程序,请不要使用CreateThread(),而是使用_beginthreadex()。

_beginthreadex()将初始化C / C ++运行库,但CreateThread()不会。

答案 2 :(得分:1)

线程是当前占用CPU的上下文,是Windows CE调度的部分。

要创建线程,请使用CreateThread。您可以阅读更多线程和流​​程函数here

此信息对于Windows CE 6也是正确的。

答案 3 :(得分:0)

在维基百科中解释了很受欢迎的内容:)

http://en.wikipedia.org/wiki/Thread_%28computer_science%29

如何处理它,你可以阅读

.NET multithreading (Alan Dennis) isbn=1930110545

答案 4 :(得分:0)

所有这些答案建议使用CreateThread()

这只是糟糕的建议。

通常应使用_beginthread()_beginthreadex()创建线程,以确保适当初始化C / C ++运行时线程局部结构。

有关详细信息,请参阅有关此问题的讨论:Windows threading: _beginthread vs _beginthreadex vs CreateThread C++