C++使用Windows API CreateMutex函数多线程编程
生活随笔
收集整理的這篇文章主要介紹了
C++使用Windows API CreateMutex函数多线程编程
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C++中也可以使用Windows 系統(tǒng)中對(duì)應(yīng)的API函數(shù)進(jìn)行多線程編程。使用CreateThread函數(shù)創(chuàng)建線程,并且可以通過CreateMutex創(chuàng)建一個(gè)互斥量實(shí)現(xiàn)線程間數(shù)據(jù)的同步:
#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"); //創(chuàng)建互斥量HANDLE hThread = CreateThread(NULL, 0, thread01, NULL, 0, NULL); //創(chuàng)建線程01hThread = CreateThread(NULL, 0, thread02, NULL, 0, NULL); //創(chuàng)建線程01CloseHandle(hThread); //關(guān)閉句柄system("pause");return 0; }
輸出:
轉(zhuǎn)載于:https://www.cnblogs.com/mtcnn/p/9411888.html
總結(jié)
以上是生活随笔為你收集整理的C++使用Windows API CreateMutex函数多线程编程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国科学院大学2014年数学分析高等代数
- 下一篇: jqueryGannt用法