(SDK)多線程單線程比較演示程序

需要在VC中設置好使用多線程運行時庫,否則程序無法識別_beginthread函數,運行時需要在命令行帶參運行。例如mt 0 30 30 0 0表示多線程,主線程和從線程計數均爲20,均不發聲。 
 
/**************************
Wandy Wang   2005-3-27
 
單線程與多線程演示程序
 
***************************/
// compile with: /MT /D "_X86_" /c
 
#i nclude <windows.h>
#i nclude <stdio.h>
#i nclude <process.h>
#i nclude <dos.h>
#i nclude <string.h>
 
int t1Snd,t2Snd;
 
//線程函數
void fun(void* para)
{
 int i=0;
 for(i=0;i<=atoi((char*)para);i++)
 {
    printf("+++++i=%d/n",i);  
       if(t2Snd) MessageBeep(MB_ICONEXCLAMATION);
 }
}
 
//主函數
void main(int argc,char* argv[])
{
   //函數介紹及使用提示
   printf( "演示但線程與多線程區別的程序/n");
  
   //參數解析說明
   //0 路徑
   //1 程序類型 1單線程 0多線程
   //2 主線程計數值
   //3 次線程計數值
   //4 主線程發聲與否
   //5 從線程發聲與否
   int single,t1Cnt,t2Cnt;
  
   if(argc!=6)
   {
          printf("參數個數不對,必須爲6個參數");
          printf("/n正確調用方式:mt 1 30 30 0 0/n參數解釋:多線程,主線程計數,從線程計數,主線程不發聲,從線程不發聲/n參數可以相應改變,須在命令行下執行/n");
          getchar();         
          return;
   }
   else
   {  
          single=atoi(argv[1]);
          t1Cnt=atoi(argv[2]);
          t2Cnt=atoi(argv[3]);
          t1Snd=atoi(argv[4]);
          t2Snd=atoi(argv[5]);
 
          printf("/n可執行文件名:%s",argv[0]);
          printf("/n程序類型:%s",single?"單線程":"多線程");
                      printf("/n主線程計數值:%d",t1Cnt);
          printf("/n次線程計數值:%d",t2Cnt);
          printf("/n主線程發聲與否:%s",t1Snd?"是":"否");
          printf("/n從線程發聲與否:%s",t2Snd?"是":"否");  
   }       
 
   //等待開始
   getchar();
  
   char string[10];
  
   //單線程或創建多線程輸出
   if(single)
   {
      fun((void*)itoa(t2Cnt,string,10));     
   }
   else
   {
         _beginthread(fun,0,(void*)itoa(t2Cnt,string,10));//創建新線程
   }
  
   //主線程輸出
   int j=0;
   for(j=0;j<=t1Cnt;j++)
   {
     printf("-----j=%d/n",j);
        if(t1Snd) MessageBeep(MB_ERROR);
   } 
 
  
   //輸出完後暫停看屏幕輸出
   getchar();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章