#include <Afxwin.h>#include <Afxmt.h>#include <iostream>#include <deque>#include <string>
class A {
int id;
public:
mutable CSemaphore semaphore; bool stop; bool active;
A(int idT):
semaphore(), stop(false), active(true), id(idT) {
}
A(const A &a):
semaphore(), id(a.id) {
a.semaphore.Lock();
stop=a.stop;
active=a.active;
a.semaphore.Unlock();
}
int getId() const {
return id;
}
};
unsigned int controllingFunction(LPVOID pObject)
{
A *pA=(A *)pObject;
while(true)
{
std::cerr<<"Hilo número: "<<pA->getId()<<'\n';
pA->semaphore.Lock();
if(pA->stop) {
std::cerr<<"[[[ Hilo terminado: "<<pA->getId()<<" ]]]\n";
pA->active=false; pA->semaphore.Unlock();
break;
}
pA->semaphore.Unlock();
Sleep(2000); }
return 0;}
bool someActive(const std::deque<A> &d)
{
for(std::deque<A>::const_iterator it=d.begin(); it!=d.end(); ++it)
{
it->semaphore.Lock();
if(it->active)
{
it->semaphore.Unlock();
return true;
}
it->semaphore.Unlock();
}
return false;
}
void stopThread(std::deque<A> &d, int aID)
{
for(std::deque<A>::iterator it=d.begin(); it!=d.end(); ++it)
{
if(it->getId()==aID)
{
it->semaphore.Lock();
if(!it->stop)
{
it->stop=true;
}
it->semaphore.Unlock();
}
}
}
void stopThreads(std::deque<A> &d)
{
for(std::deque<A>::iterator it=d.begin(); it!=d.end(); ++it)
{
it->semaphore.Lock();
if(!it->stop)
{
it->stop=true;
}
it->semaphore.Unlock();
}
}
void main()
{
std::deque<A> dA;
int id;
std::string s, squit("exit"), skill("kill");
dA.push_back(A(1));AfxBeginThread(controllingFunction,(LPVOID)&dA[dA.size()-1]);dA.push_back(A(2));AfxBeginThread(controllingFunction,(LPVOID)&dA[dA.size()-1]);
while(true)
{
std::cerr<<':'; std::cin>>s; if(s==squit) {
stopThreads(dA); break;
}
else if(s==skill) {
std::cin.get();
if(std::cin.rdbuf()->in_avail()) {
id=0;
std::cin>>id;
stopThread(dA,id); }
else
stopThreads(dA); }
else
{
std::cerr<<"Orden desconocida\n";
}
}
while(someActive(dA)) ;
}