C语言Win32多线程简单例子

来自http://tunps.com/c-win32-simple-multithreads

#include <windows.h>
#include <stdio.h>
#include <process.h>
// Secound Thread function
void ThreadProc(void *param);
 
// First thread
int main()
{
 
    int n;
    int i;
    int val = 0;
    HANDLE handle;
 
    printf("\t Thread Demo\n");
 
    printf("Enter the number of threads : ");
    scanf("%d",&n);
 
    for(i=0;i<n ;i++)
    {
        val = i+1;
        handle = (HANDLE) _beginthread( ThreadProc,0,&val); // create thread
        WaitForSingleObject(handle,INFINITE);
 
    }
 
    return 0;
}
 
void ThreadProc(void *param)
{
 
    int h=*((int*)param);
    printf("%d Thread is Running!\n",h);
    Sleep(1000);
    _endthread();
 
}
功能是执行用户键入指定数量的线程,每个线程干同样的事情:输出字符串:某Thread is Running!,然后Sleep 1秒钟,结束进程,WaitForSingleObject等待指定对象进入有信号的状态,或者等待指定时间。 另外发现一个监视线程活动的好工具,sysinternal的Process Monitor : 参考:http://www.codeproject.com/KB/threads/crtmultithreading.aspx

About tunpishuang

just 4 fun·····
This entry was posted in 未分类 and tagged , , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>