从孙鑫c++教程学的 但是执行时一个线程有时会运行两遍 有时输出还很混乱
比如会输出
Thread1 sell ticket:100
Thread1 sell ticket:100
Thread2 sell ticket:99
还有时候输出
Thread1 sell ticket:Thread2 sell ticket 2625
操作系统是win7 是操作系统的问题?还是双核的问题?
#include<iostream.h>
#include<windows.h>
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
);
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
);
int ticket=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);
HANDLE hThread2;
hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//cout<<"MainThread is running!"<<endl;
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(1000);
return;}
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
)
{
while(ticket)
{
WaitForSingleObject(hMutex,0);
cout<<"Thread1 sell ticket:"<<ticket--<<endl;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
)
{
while(ticket)
{
WaitForSingleObject(hMutex,0);
cout<<"Thread2 sell ticket:"<<ticket--<<endl;
ReleaseMutex(hMutex);
}
return 0;
}
比如会输出
Thread1 sell ticket:100
Thread1 sell ticket:100
Thread2 sell ticket:99
还有时候输出
Thread1 sell ticket:Thread2 sell ticket 2625
操作系统是win7 是操作系统的问题?还是双核的问题?
#include<iostream.h>
#include<windows.h>
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
);
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
);
int ticket=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);
HANDLE hThread2;
hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//cout<<"MainThread is running!"<<endl;
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(1000);
return;}
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
)
{
while(ticket)
{
WaitForSingleObject(hMutex,0);
cout<<"Thread1 sell ticket:"<<ticket--<<endl;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
)
{
while(ticket)
{
WaitForSingleObject(hMutex,0);
cout<<"Thread2 sell ticket:"<<ticket--<<endl;
ReleaseMutex(hMutex);
}
return 0;
}
解决方案 »
- byte 表示范围是-128 至 127 . 那么-128是如何表示出来呢?
- java简单输入输出问题
- 求助:JSP 连接 数据库 出现问题
- 请问那位高手可以帮我看一下这个程序什么地方有错???急!谢谢了!
- 问什么在jsp中出现乱码
- 绿色版tomcat 重装JDK后,服务起不来
- com.microsoft.sqlserver.jdbc.SQLServerException: 索引 2 超出范围。
- 用什么方法进行类型转换?很简单。
- 请问哪里有《Thinking in Java》中文第二版的电子书和源代码可以下载?
- java中使用Object类中比较遇到的问题,请帮忙解答一下。
- 怎么错了
- 双色球代码出现null值 求大神现身相助
去C++版再发一遍吧。