• Win32 API 多线程编程——一个简单实例(含消息参数传递)


    Win32 API进行程序设计具有很多优点:应用程序执行代码小,运行效率高,但是他要求程序员编写的代码较多,且需要管理所有系统提供给程序的资源,要求程序员对Windows系统内核有一定的了解,会占用程序员很多时间对系统资源进行管理,因而程序员的工作效率降低。

    简单实例

     1 #include <iostream>
     2 #include <windows.h>
     3 using namespace std;
     4 
     5 DWORD WINAPI ThreadProc1(LPVOID lpParameter)
     6 {
     7 
     8     for (int i = 0; i < 10; i++)
     9     {
    10         cout << "我是子线程1" << "  " << i << endl;
    11     }
    12     return 0;
    13 }
    14 
    15 DWORD WINAPI ThreadProc2(LPVOID lpParameter)
    16 {
    17     cout << "我是子线程2" << endl;
    18     return 0;
    19 }
    20 
    21 void main()
    22 {
    23     HANDLE hThread1,hThread2;
    24     hThread1 = CreateThread(NULL, NULL, ThreadProc1, NULL, NULL, NULL);
    25     hThread2 = CreateThread(NULL, NULL, ThreadProc2, NULL, NULL, NULL);
    26     WaitForSingleObject(hThread1, INFINITE);  //同步
    27     WaitForSingleObject(hThread2, INFINITE);
    28     cout << "我是主线程" << endl;
    29     while (1);
    30 }
    View Code

     含参数传递的实例

     1 #include <iostream>
     2 #include <windows.h>
     3 using namespace std;
     4 class DATA
     5 {
     6 public:
     7     int a=0;
     8     int b=0;
     9     int c=0;
    10 public:
    11     DATA()
    12     {
    13         a = 1; b = 2; c = 3;
    14     }
    15     DATA(int aa, int bb, int cc)
    16     {
    17         a = aa;
    18         b = bb;
    19         c = cc;
    20     }
    21 };
    22 
    23 DWORD WINAPI ThreadProc1(LPVOID lpParameter)
    24 {
    25     DATA* d = (DATA*)lpParameter;
    26 
    27     for (int i = 0; i < 10; i++)
    28     {
    29         cout << "我是子线程1" << "  " << i << endl;
    30         cout << d->a << endl;
    31     }
    32     return 0;
    33 }
    34 
    35 DWORD WINAPI ThreadProc2(LPVOID lpParameter)
    36 {
    37     cout << "我是子线程2" << endl;
    38     return 0;
    39 }
    40 
    41 void main()
    42 {
    43     HANDLE hThread1, hThread2;
    44     DATA *d = new DATA(10,20,30);
    45     hThread1 = CreateThread(NULL, NULL, ThreadProc1, d, NULL, NULL);
    46     hThread2 = CreateThread(NULL, NULL, ThreadProc2, NULL, NULL, NULL);
    47     WaitForSingleObject(hThread1, INFINITE);
    48     WaitForSingleObject(hThread2, INFINITE);
    49     cout << "我是主线程" << endl;
    50     while (1);
    51 }
    View Code

    LPVOID是个传递参数的玩意,无实际类型 ,大致就是这么用。

  • 相关阅读:
    Github的基本使用
    Java Web工程搭建方法
    程序中使用百度地图
    Flutter 依赖的那些事儿
    Flutter Widgets (Container/Row/Column/Image)
    Flutter 安装
    UWP FillRowViewPanel
    UWP Composition API
    UWP Composition API
    UWP Jenkins + NuGet + MSBuild 手把手教你做自动UWP Build 和 App store包
  • 原文地址:https://www.cnblogs.com/starf/p/3623703.html
Copyright © 2020-2023  润新知