【VC开源代码栏目提醒】:文章导读:在新的一年中,各位网友都进入紧张的学习或是工作阶段。网学会员整理了VC开源代码-thread_14.cpp的相关内容供大家参考,祝大家在新的一年里工作和学习顺利!
#include<windows.h>
#include<iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParaneter
);
DWORD WINAPI Fun2Proc(
LPVOID lpParaneter
);
int time=0;
HANDLE sema;
void main()
{
HANDLE thread1,thread2;
thread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); //创建线程
thread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(thread1);
CloseHandle(thread2);
sema=CreateSemaphore(NULL,1,1,NULL); //创建信号量
Sleep(4000);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParaneter
)
{
while(1)
{
WaitForSingleObject(sema,INFINITE);
if(time<=20)
{
Sleep(1);
cout<<"子线程1第"<<time++<<"次"<<endl;
}
else
break;
ReleaseSemaphore(sema,1,NULL); //关闭信号量
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParaneter
)
{
while(1)
{
WaitForSingleObject(sema,INFINITE);
if(time<=20)
{
Sleep(1);
cout<<"子线程2第"<<time++<<"次"<<endl;
}
else
break;
ReleaseSemaphore(sema,1,NULL);
}
return 0;
}