VC6.0下创建多线程的方法和注意的事项

来源:互联网 发布:东京大学 知乎 编辑:程序博客网 时间:2024/05/09 02:03
#include<stdio.h>
#include <process.h>
#include <stdio.h>
#include <windows.h>
DWORD _stdcall ThreadProc(LPVOID lpParameter)//线程执行函数
{
int si=100;
while(si>0)
{
printf("子线程输出数字:%d\n",si--);
Sleep(1000);
}
return 0;
}


int main()
{
int mi=0;
CreateThread(NULL,0,ThreadProc,NULL,0,NULL);//创建一个线程,去执行ThreadProc函数

while(mi<100)
{
printf("主线程输出数字:%d\n",mi++);
Sleep(1000);
}
return 0;

}

这一段代码没问题,但是要将CreateThread()换成_beginthreadex()的话就会出错!!!

#include<stdio.h>
#include <process.h>
#include <stdio.h>
#include <windows.h>
unsigned _stdcall ThreadProc1(LPVOID lpParameter)//线程执行函数1
{
int si=100;
while(si>0)
{
printf("子线程:%d\n",si--);
Sleep(1000);
}
return 0;
}


int main()
{
int mi=0;

HANDLE   hth1;
unsigned  uiThread1ID;
hth1 = (HANDLE)_beginthreadex( NULL, 0,ThreadProc1,NULL,  
                              CREATE_SUSPENDED,&uiThread1ID );
if(hth1 == NULL)
{
return FALSE;
}
else
{
ResumeThread(hth1);
}
while(mi<100)
{
printf("主线程输出数字:%d\n\n",mi++);
Sleep(1000);
}
return 0;
}

运行之后会出现错误_beginthreadex()没有定义。这时候需要你改变设置。

_beginthreadex不仅要加头文件“process.h”还要设置工程属性;


在VC6下用_beginthreadex编写多线程程序时,不但要将<process.h>包含进来,而且还是设置工程属性,选择C/C++

一栏,在分类里选择Code Generation,在Use run-time library那一个栏选择多线程版本(带有Multithreaded的)就可以了。



2 0