首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

关于线程的一个程序,请问一上

2012-12-16 
关于线程的一个程序,请教一下。本帖最后由 sunhui8809075 于 2012-11-16 21:01:05 编辑include windows.h

关于线程的一个程序,请教一下。
本帖最后由 sunhui8809075 于 2012-11-16 21:01:05 编辑


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

#define MAX_THREAD_NUM  2

void control_thread( void );
void worker_thread( void );


////////////////////////////////////////////////////////
// main fuction
////////////////////////////////////////////////////////

int main( int agrc, char* argv[] )
{
char ch;

while ( TRUE )
{
// Cleare screen
system( "cls" );

// display prompt info
printf("*********************************************\n");
printf("       1.Start test\n");
printf("       2.Exit to Windows\n");
printf("*********************************************\n");
printf("Input your choice(1or2): ");

// if the number inputed is error, retry!
do{
ch = (char)_getch(); 
}while( ch != '1' && ch != '2');

system ( "cls" );
if ( ch == '1')
control_thread();
else if ( ch == '2')
return 0;
printf("\nPress any key to finish this Program. \nThank you test this Proggram!\n");
_getch();
} //end while
} //end main

void control_thread( void )
{
DWORD n_thread = 2;
DWORD thread_ID;
DWORD wait_for_all;

// Tread Object Array

HANDLE h_Thread[MAX_THREAD_NUM];

// Create thread
h_Thread[0] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)(worker_thread), 0, 0, &thread_ID);
//h_Thread[1] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)(worker_thread), 0, 0, &thread_ID);

// waiting all thread will been finished

wait_for_all = WaitForMultipleObjects(n_thread,h_Thread,TRUE, -1);
printf("All threads have finished Operating.\n");
}// end


// thread
void worker_thread(void)
{
int i;
for( i=0; i<10; i++)
{
printf("x= %05d\n",i);
Sleep(1000);  //wait a moment
}
}

我注释掉“h_Thread[1] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)(worker_thread), 0, 0, &thread_ID);
”这句之后为什么输出是这样:

红色部分是怎么回事?
[最优解释]

if ( ch == '1'){ 
   control_thread();   
}else if ( ch == '2'){       
   return 0;    
}     

printf("\nPress any key to finish this Program. \nThank you test this Proggram!\n"); 

你的代码就这样写的。
[其他解释]
因为 h_Thread 没有初始化 WaitForMultipleObjects 应该是返回 WAIT_FAILED, 而你并没有判断返回值

[其他解释]


你注释掉h_Thread[1]以后,你的


WaitForMultipleObjects(n_thread,h_Thread,TRUE, -1);

中只有一个h_Thread[0]是有效的
[其他解释]
WaitForMultipleObjects

第三个参数
是TRUE的话,要等所有的h_Thread一起返回。
是FALSE的话,任何一个返回h_Thread返回即可。

热点排行