我有以下程序:問題在程序執行的線程
#include "stdafx.h"
#include <boost/thread/thread_time.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
using namespace std;
class DogDoor {
bool open;
public:
DogDoor()
{
this->open = false;
}
void Open()
{
cout << "The dog door opens" << endl << endl;
open = true;
}
void close()
{
cout << "The dog door closes" << endl << endl;
open = false;
}
bool isOpen()
{
return open;
}
};
class Remote {
DogDoor* door;
public:
Remote(DogDoor* door)
{
this->door = door;
}
void pressButton()
{
cout << "Pressing the remote button" << endl;
if(door->isOpen())
{
door->close();
}
else
{
door->Open();
// close after 5 seconds
boost::posix_time::seconds workTime(5);
boost::this_thread::sleep(workTime);
door->close();
}
}
};
void threadFunc(Remote* r)
{
r->pressButton();
}
int _tmain(int argc, _TCHAR* argv[])
{
DogDoor* door = new DogDoor();
Remote* remote = new Remote(door);
cout << "Fido barks to go outside" << endl;
boost::thread workerThread(threadFunc, remote);
cout << "Fido has gone outside" << endl;
cout << "Fido is all done..." << endl;
cout << "Fido is back inside" << endl;
workerThread.join();
delete door;
delete remote;
return 0;
}
我希望程序打印:
Fido barks to go outside
Pressing the remote button
The dog door opens
Fido has gone outside
Fido is all done...
Fido is back inside
// and then after 5 seconds it should print this
The dog door closes
但我實現它會打印這樣的,我不知道如何使它打印良好:
Fido barks to go outside
Fido has gone outside
Fido is all done...
Fido is back inside
Pressing the remote button
The dog door opens
// this after 5 seconds
The dog door closes
非常感謝你 – Kobe 2011-03-22 22:25:38