线程同步-互锁函数
- 互鎖函數:
- LONG InterlockedIncrement(LONG volatile* Addend):遞增指定32位變量,增量位1,可以阻止其他線程同時使用此變量;
- LONG InterlockedDecrement(LONG volatile* Addend):遞減指定的32變量,減小量位1;
#include<windows.h>
#include<iostream>
#include<process.h>
using namespace std;
UINT __stdcall ThreadProcess(LPVOID lpParam);
int b = true;
int count1 = 0;
int count2 = 0;
int main()
{
?? ?UINT Ui;
?? ?HANDLE hThread[10];
?? ?for (int i = 0; i < 10; i++)
?? ?{
?? ??? ?hThread[i] = (HANDLE)::_beginthreadex(NULL, 0, ThreadProcess, NULL, 0, &Ui);
?? ?}
?? ?Sleep(6000);
?? ?b = false;
?? ?::WaitForMultipleObjects(10, hThread, TRUE, INFINITE);
?? ?for (int i = 0; i < 10; i++)
?? ?{
?? ??? ?::CloseHandle(hThread[i]);
?? ?}
?? ?cout << "Count1=" << count1 << endl;
?? ?cout << "Count2=" << count2 << endl;
?? ?return 0;
}
UINT __stdcall ThreadProcess(LPVOID lpParam)
{
?? ?while (b)
?? ?{ ?
? ? ? ? //做加以操作
?? ??? ?::InterlockedIncrement((long*)&count1);
?? ??? ?::InterlockedIncrement((long*)&count2);
?? ??? ?//count1++;
?? ??? ?//count2++;
?? ?}
?? ?return 0;
}
總結
- 上一篇: 第二章 数据的表示和运算 2.1.1 进
- 下一篇: Leetcode--1014. 最佳观光