VC++.net关于多线程

weweken520 2008-11-12 04:35:55
谁能给我一个关于VC++.net的多线程的例子,我的程序在处理的时候会处于假死锁态,应该是多线程就可以解决这个问题了,谁能提供一个相似的例子我,万分感谢,以后将和你资源共享。 我的msn是weweken@hotmail.com
...全文
51 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cowcs 2008-11-14
  • 打赏
  • 举报
回复
呵呵,我给你发了一个了,你看看吧,是一个用事件使线程同步的小列子,希望有用。
weweken520 2008-11-14
  • 打赏
  • 举报
回复
结贴,谢谢。
weweken520 2008-11-14
  • 打赏
  • 举报
回复
结贴,谢谢。
liuweibit 2008-11-13
  • 打赏
  • 举报
回复

#include <windows.h>
#include <iostream.h>

DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);

DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE 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;*/
//hMutex=CreateMutex(NULL,TRUE,NULL);
hMutex=CreateMutex(NULL,TRUE,"tickets");
if(hMutex)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only instance can run!"<<endl;
return;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);
// Sleep(10);
}

DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
/*while(index++<1000)
cout<<"thread1 is running"<<endl;*/

/*while(TRUE)
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}*/

WaitForSingleObject(hMutex,INFINITE);
cout<<"thread1 is running"<<endl;
return 0;
}

DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{

/*while(TRUE)
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}*/
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread2 is running"<<endl;
return 0;
}


这是一个多线程的程序!希望对你有帮助!

7,540

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 VC.NET
社区管理员
  • VC.NET社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧