【发布时间】:2013-09-05 01:49:51
【问题描述】:
我有一个带有套接字通信类的 c++ 程序。每个插座都有一个大的专用 用于组装输出消息的缓冲区,因此用法如下:
class CSocketClass {
public:
SetMsgHeader(int n) { Mutex_.lock(); DoWhateverIsNeededToSetHeaderInBuffer(n); } // where n would be the message type
SetMsgField(double a); { DoWhateverIsNeededToSetDataInBuffer(a); } // where a would be some arbitrary content
SendMsg(); { DoWhateverIsNeededToSendBuffer(); Mutex_.unlock(); } // where this would send the number of bytes added to the buffer since the header was set
private:
char buffer[reallylarge];
MiscSocketApparatus...
boost::mutex Mutex_;
};
多个线程可能正在尝试发送消息,每个线程由三个或更多调用组成,设置标题、内容,并最终在其途中发送消息。为了避免它们发生冲突,我尝试使用互斥锁一次只保留一个作家。期望的行为是阻止第二个到达的写入器,直到第一个到达的写入器解锁互斥锁。然后被阻止的写入器将能够继续。
这似乎大部分时间都有效,但在极少数情况下(不是每天),死锁似乎仍然会发生。
我更熟悉使用范围锁的更简单的锁问题,但这些概念可能无法完美地转化为这个问题,在这个问题上,锁需要在对拥有锁的对象的多次调用中保持不变。
通过阅读 Boost 同步教程,我认为有更好的方法可以做到这一点,但不清楚哪种方法最好。
任何建议将不胜感激。
【问题讨论】:
标签: c++ multithreading sockets boost