关于多线程编程的一个程序
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter);
int index = 0;
int tickets = 100;
HANDLE hMutex;
void main()
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
/*while(index ++ <1000)
cout << "main thread is running" << endl;*/
//Sleep(10);
hMutex = CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter)
{
/*while(index ++ <1000)
cout << "thread1 is running" << endl;
return 0;*/
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets > 0)
{
//Sleep(10)
cout << "thread1 sell ticket : " << tickets -- <<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets > 0)
{
//Sleep(10);
cout << "thread2 sell ticket : " << tickets -- <<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
这个是孙鑫老师视频中的源码,为什么我打印的时候会出现2行 打印100的
有时候是乱码,后面大部分显示正常
还有一个奇怪的现象是 ,如果第一个函数使用了Sleep,那么应该先打印的是thread2 sell ticket
为什么有时候会先打印出thread1
我的猜想是我的是双核CPU,不知道大家怎么认为呢,
谢谢大家帮忙