dimanche 26 avril 2015

Is this multithreaded code correct?

I want to create have two threads running in the program. A main thread which can serve any of the public functions (API calls) in my client and another background thread which wakes up every X seconds and calls a PING api in my client. How do I do this efficiently so that there are no race conditions? shared access is synchronized? How do I spawn this thread through a constructor? And How do I destroy this thread in the destructor ?

// MyClient.h

 const static int sleepMillis = 120000;
 std::atomic<bool> m_pingRunning;
 std::mutex g_i_mutex;  

// MyClient.cpp
class MyClient {

private void start() {
m_pingRunnning = true;
}

private void stop() {
m_pingRunning = false;
}

private void dispatch() {
while(m_pingRunning) {
// create a SendPing request.
sendPing(request);
std::this_thread::sleep_for(std::chrono::milliseconds(m_sleepMillis));
}

}

public void MyClient::SendPing(const SendPingRequest& request) const {
// synchronously SendPing to the server
}
}

Aucun commentaire:

Enregistrer un commentaire