zoukankan      html  css  js  c++  java
  • C++使用Windows API CreateMutex函数多线程编程

    C++中也可以使用Windows 系统中对应的API函数进行多线程编程。使用CreateThread函数创建线程,并且可以通过CreateMutex创建一个互斥量实现线程间数据的同步:


    #include <iostream>
    #include <Windows.h>
    
    using namespace std;
    
    HANDLE hMutex = NULL; //互斥量
    
    DWORD WINAPI thread01(LPVOID lvParamter)
    {
    	for (int i = 0; i < 10; i++)
    	{
    		WaitForSingleObject(hMutex, INFINITE); //互斥锁
    		cout << "Thread 01 is working!" << endl;
    		ReleaseMutex(hMutex); //释放互斥锁
    	}
    	return 0;
    }
    
    DWORD WINAPI thread02(LPVOID lvParamter)
    {
    	for (int i = 0; i < 10; i++)
    	{
    		WaitForSingleObject(hMutex, INFINITE); //互斥锁
    		cout << "Thread 02 is working!" << endl;
    		ReleaseMutex(hMutex); //释放互斥锁
    	}
    	return 0;
    }
    
    
    int main()
    {
    	hMutex = CreateMutex(NULL, FALSE, (LPCWSTR)"Test"); //创建互斥量
    	HANDLE hThread = CreateThread(NULL, 0, thread01, NULL, 0, NULL);  //创建线程01
    	hThread = CreateThread(NULL, 0, thread02, NULL, 0, NULL);     //创建线程01
    	CloseHandle(hThread); //关闭句柄
    	system("pause");
    	return 0;
    }


    输出:


  • 相关阅读:
    linux系统中不同颜色的文件夹及根目录介绍
    linux命令学习 随笔
    Happiness
    Sequence Number
    base64加密解密c++代码
    Wooden Sticks
    出租车费
    关系推断
    如何在Ubuntu中安装中文输入法
    c语言中printf("%x",-1);为什么会输出-1的十六进制补码??
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9411888.html
Copyright © 2011-2022 走看看