不使用互斥 2个线程输出数组arr
HANDLE hMutex = NULL;
int arr[5] = {1, 2, 3, 4, 5};
DWORD CALLBACK Thread1(LPVOID Param)
{
while(true)
{
//WaitForSingleObject(hMutex, INFINITE);
cout << "Thread1:/t";
for (int i = 0; i < 5; i++)
{
cout << arr[i] << ' ';
Sleep(50);
}
cout << endl;
//ReleaseMutex(hMutex);
}
}
DWORD CALLBACK Thread2(LPVOID Param)
{
while(true)
{
//WaitForSingleObject(hMutex, INFINITE);
cout << "Thread2:/t";
for (int i = 0; i < 5; i++)
{
cout << arr[i] << ' ';
Sleep(50);
}
cout << endl;
//ReleaseMutex(hMutex);
}
}
int main()
{
//hMutex = CreateMutex(NULL, NULL, NULL);
CreateThread(NULL, 0 ,Thread1, NULL, NULL, NULL);
CreateThread(NULL, 0 ,Thread2, NULL, NULL, NULL);
while(true)
{
Sleep(100);
}
return 0;
}
结果:
使用互斥的输出:
HANDLE WINAPI CreateMutex(
__in LPSECURITY_ATTRIBUTES lpMutexAttributes,
__in BOOL bInitialOwner,
__in LPCTSTR lpName
);
DWORD WINAPI WaitForSingleObject(
__in HANDLE hHandle,
__in DWORD dwMilliseconds
);
The WaitForSingleObject function can wait for the following objects:
- Change notification
- Console input
- Event
- Memory resource notification
- Mutex
- Process
- Semaphore
- Thread
- Waitable timer
主线程利用WaitForSingleObject等待另一个线程结束:
int arr[5] = {1, 2, 3, 4, 5};
DWORD CALLBACK Thread1(LPVOID Param)
{
for(int c = 0; c < 10; c++)
{
cout << "Thread1:/t";
for (int i = 0; i < 5; i++)
{
cout << arr[i] << ' ';
Sleep(50);
}
cout << endl;
}
return 0;
}
HANDLE hThread1 = NULL;
int main()
{
hThread1 = CreateThread(NULL, 0 ,Thread1, NULL, NULL, NULL);
WaitForSingleObject(hThread1, INFINITE);
return 0;
}