多线程程序的建立

来源:互联网 发布:3d66软件免费下载 编辑:程序博客网 时间:2024/06/05 08:51
多线程序是开发过程中经常要用到的一个技术.对网络应用程序更是如此,在服务器端中要为多用户服务.多线程是首选.
   下面是一个多线程例子:
       #include<iostream.h>
       #include<process.h>
       #include<windows.h>
       #include<stdio.h>
       BOOL flag = true ;
       DWORD WINAPI Thread1(LPVOID lpParamter)
       {
          while(flag)
          {
            cout<<"thread1 开始运行....."<<endl;
          }
          return 0 ;
       }
      DWORD WINAPI Thread2(LPVOID lpParamter)
      {
         while(flag)
         {
            cout<<"thread2 开始运行....."<<endl;
         }
         return 0 ;
      }
      DWORD WINAPI Thread3(LPVOID lpParamter)
      {
 
          flag = false ;
          cout<<"thread3 开始运行....."<<endl;
          return 0 ;
      }
      void main()
      {
         HANDLE thread1,thread2,thread3;
         DWORD d1,d2,d3;
         thread1 = CreateThread(NULL,0,Thread1,NULL,0,&d1);
         if(thread1 == NULL)
         {
            cout<<"线程一创建失败......"<<endl;
         }
         thread2 = CreateThread(NULL,0,Thread2,NULL,0,&d2);
         if(thread2 == NULL)
         {
            cout<<"线程二创建失败......"<<endl;
         }
         thread3 = CreateThread(NULL,0,Thread3,NULL,0,&d3);
         if(thread3 == NULL)
         {
            cout<<"线程三创建失败......"<<endl;
         }
         Sleep(2000);
 
         CloseHandle( thread1 );
         CloseHandle( thread2 );
         CloseHandle( thread3 );
      }
 
   这是一个线程的创建与调用.有三个自已创建的线程.CreateThread()是线程创建函数.其中前两个参数可以为NULL,0.第三个参数为调用函数.为线程功能的实现.另外第四个参数为参数信息,可以为空.第五个为NULL,第六个为0,第七个为线程ID.线程实体函数的格式为:DWORD WINAPI ThreadProc( LPVOID lpParameter );在这个函数体内我们可以自定义自已想要实现的内容就可以了.
 
原创粉丝点击