我需要有一个具有一个活动的类,该活动在其自己的线程中每 5 秒执行一次。它是一种 Web 服务,因此需要指定一个端点。在对象运行时,主线程可以更改端点。这是我的课:
class Worker
{
public:
void setEndpoint(const std::string& endpoint);
private:
void activity (void);
mutex endpoint_mutex;
volatile std::auto_ptr<std::string> newEndpoint;
WebServiceClient client;
}
newEndpoint 对象是否需要声明为 volatile?如果读取处于某个循环中(以使编译器不对其进行优化),我当然会这样做,但在这里我不知道。
在每次运行中,该activity()
函数都会检查新端点(如果有新端点,则将其传递给客户端并执行一些重新连接步骤)并完成其工作。
void Worker::activity(void)
{
endpoint_mutex.lock(); //don't consider exceptions
std::auto_ptr<std::string>& ep = const_cast<std::auto_ptr<string> >(newEndpoint);
if (NULL != ep.get())
{
client.setEndpoint(*ep);
ep.reset(NULL);
endpoint_mutex.unlock();
client.doReconnectionStuff();
client.doReconnectionStuff2();
}
else
{
endpoint_mutex.unlock();
}
client.doSomeStuff();
client.doAnotherStuff();
.....
}
我锁定了互斥体,这意味着 newEndpoint 对象不能再更改,因此我删除了volatile类规范以便能够调用const方法。
setEndpoint 方法(从另一个线程调用):
void Worker::setEndpoint(const std::string& endpoint)
{
endpoint_mutex.lock(); //again - don't consider exceptions
std::auto_ptr<std::string>& ep = const_cast<std::auto_ptr<string> >(newEndpoint);
ep.reset(new std::string(endpoint);
endpoint_mutex.unlock();
}
这东西线程安全吗?如果不是,问题是什么?我需要 newEndpoint 对象是易变的吗?