C++中线程的切换
#include<iostream.h>
#include<windows.h>
DWORD WINAPI ThreadProc1(
LPVOID lpParameter // thread data
);
DWORD WINAPI ThreadProc2(
LPVOID lpParameter // thread data
);
int tickets=20;
void main()
{
HANDLE hThread1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
HANDLE hThread2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cout<<"the main thread is running:"<<endl;
Sleep(4000);
cout<<"the main thread is over!"<<endl;
}
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
while(1)
{
if(tickets>0)
{
cout<<"ThreadProc1 sells ticket's num:"<<tickets--<<endl;
}
}
}
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
while(1)
{
if(tickets>0)
{
cout<<"ThreadProc2 sells ticket's num:"<<tickets--<<endl;
}
}
}
#include<iostream.h>
#include<windows.h>
DWORD WINAPI ThreadProc1(
LPVOID lpParameter // thread data
);
DWORD WINAPI ThreadProc2(
LPVOID lpParameter // thread data
);
int tickets=20;
void main()
{
HANDLE hThread1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
HANDLE hThread2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cout<<"the main thread is running:"<<endl;
Sleep(4000);
cout<<"the main thread is over!"<<endl;
}
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
while(1)
{
if(tickets>0)
{
cout<<"ThreadProc1 sells ticket's num:"<<tickets--<<endl;
}
}
}
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
while(1)
{
if(tickets>0)
{
cout<<"ThreadProc2 sells ticket's num:"<<tickets--<<endl;
}
}
}
the main thread is running:
ThreadProc1 sells ticket's num:20
ThreadProc1 sells ticket's num:19
ThreadProc1 sells ticket's num:18
ThreadProc1 sells ticket's num:17
ThreadProc1 sells ticket's num:16
ThreadProc1 sells ticket's num:15
ThreadProc1 sells ticket's num:14
ThreadProc1 sells ticket's num:13
ThreadProc1 sells ticket's num:12
ThreadProc1 sells ticket's num:11
ThreadProc1 sells ticket's num:10
ThreadProc1 sells ticket's num:9
ThreadProc1 sells ticket's num:8
ThreadProc1 sells ticket's num:7
ThreadProc1 sells ticket's num:6
ThreadProc1 sells ticket's num:5
ThreadProc1 sells ticket's num:5
ThreadProc2 sells ticket's num:4
ThreadProc2 sells ticket's num:3
ThreadProc2 sells ticket's num:2
ThreadProc2 sells ticket's num:1
the main thread is over!
Press any key to continue
刚学线程编程,实在不懂,为什么线程1第一次切换时会输出两次5?而且还均由线程1输出!(红色代码处)还请各位指教!