Archived Forum Post

Index of archived forum posts

Question:

How to Unblock a Thread Stuck within a CkSocket Method Call?

Feb 27 '13 at 17:49

In our code, we’ve made an assumption about CkSocket::Close() and wanted to see if this is something that is legal to do or not.

The scenario is that we have 2 threads. One thread is in a loop reading a fixed sized amount of bytes with CkSocket::ReceiveBytesN(). Most of the time this thread is blocked waiting for a message. It is okay for us to call CkSocket::Close() on the other thread to unblock this thread? We are looking for the best way to signal the thread to end.

We are using the Windows C++ version of your API, in case that helps.


Answer

No, this wouldn't be the suggested solution -- and I'm not sure if it would work.

A little background: The Chilkat C++ classes are thread-safe. Mostly what that means is if one method call is in progress, then another method call on the same object instance from a different thread should block until the 1st thread's call returns. However, the CkSocket is designed to be bidirectional, which means it should be possible for one thread to be writing while another thread is simultaneously reading the same CkSocket instance. Because of this, I'm not sure how the Close method call would affect the ongoing ReceiveBytesN. It may very well cause it to return with an error.

A cleaner way of doing it is to setup an event callback, like this:

class MySocketProgress: public CkSocketProgress
    {
    public:
    bool m_abort;

MySocketProgress() : m_abort(false) { }
virtual ~MySocketProgress() { }

// Called periodically during any method that communicates over the TCP connection.
// The HeartbeatMs property controls the frequency
// of callbacks.  The default HeartbeatMs value = 0, which disables
// AbortCheck callbacks.
void AbortCheck(bool *abort) 
    { 
    // To abort any operation while in progress, set the "abort" argument
    // equal to true, like this:
    *abort = m_abort;
    }

};

MySocketProgress myProgress;

void socketSample(void) { CkSocket socket;

// ....

socket.put_HeartbeatMs(100);    // Cause an AbortCheck event to happen every 10 millisec.
socket.put_EventCallbackObject(&myProgress);

// ....

CkByteData outData;
unsigned long numBytes = 100;
bool success = socket.ReceiveBytesN(numBytes,outData);

// Another thread may abort the ReceiveBytesN by setting the myProgress.m_abort = true;

}