请教一个简单的线程问题,重复输出!!
/*
05-09-15
两个线程同时对一个变量进行写操作,
他们之间的互斥的问题。
*/
#include <windows.h>
#include <iostream.h>
int tickets=20;
DWORD WINAPI FirstSell(
LPVOID lpParameter // thread data
);
DWORD WINAPI SecondSell(
LPVOID lpParameter // thread data
);
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,FirstSell,NULL,0,NULL);
hThread2=CreateThread(NULL,0,SecondSell,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(100);
}
DWORD WINAPI FirstSell(
LPVOID lpParameter // thread data
)
{
while(tickets!=0)
{
cout<<"thread1 sell:"<<tickets--<<endl;
}
return 0;
}
DWORD WINAPI SecondSell(
LPVOID lpParameter // thread data
)
{
while(tickets!=0)
{
cout<<"thread2 sells:"<<tickets--<<endl;
}
return 0;
}
上面的程序的输出是:
thread1 sell:20
thread1 sell:19
thread1 sell:18
thread1 sell:17
thread1 sell:16
thread1 sell:15
thread1 sell:14
thread1 sell:13
thread1 sell:12
thread1 sell:11
thread1 sell:10
thread1 sell:9
thread1 sell:8
thread1 sell:7
thread1 sell:6
thread1 sell:5 //重复输出的地方
thread1 sell:5
thread2 sells:4
thread2 sells:3
thread2 sells:2
thread2 sells:1
Press any key to continue
为什么在第一个线程的结束的时候,它重复的输出呢?
还请指教,谢谢!!!