How to thread a class - Client Server Program

Started by
11 comments, last by BitMaster 10 years, 4 months ago

This is getting annoying. I only posted this because it shows how you can define the methods in a class to be threaded. If you want it to be professionally used then I suggest doing all the changes that all these brilliant people pointed out to make it universally acceptable in the C++ programming community. For me, it works, it does what I need, and isn't that actually what is important. btw I wouldn't work anywhere that has C++ as its main programming language. Get current with some managed code such as C# XNA or java.

But the code doesn't define methods to be threaded. It works on your particular machine, on your particular compiler settings, for the tests you did on it, but it's not correct code. Sharing memory without synchronization primitives is undefined behavior in C++, also called "catch fire semantics" because the code is legally allowed by the C++ standard to do anything including make your computer catch fire. Furthermore, this code is the worst kind of erroneous behavior, because it works most of the time, and doesn't give an easy to trace error when it doesn't, making the errors very hard to track down.
Advertisement

If you know assembler then you'll know this is fine:

memset(this, 0x00, sizeof(Server));

It has nothing to do with assembler. And no, that's the most atrocious, evil piece of code I've ever seen and belongs in the "Coding Horrors" section of this forum.

The correct thing to do is use an initialiser list in the constructor:


Server::Server() :
    listenerIsActive( false ),
    accepterIsActive( false ),
    receiverIsActive( false ),
    receiveLength( 0 ),
    sendLength( 0 )
    /* -- etc -- */
{
}
"I would try to find halo source code by bungie best fps engine ever created, u see why call of duty loses speed due to its detail." -- GettingNifty
I wouldn't call it just that. For example, by adding the simple line
static_assert(std::is_pod<Server>::value);
would probably make it safe. I still wouldn't do it myself, but the compiler should scream at you instead of silently setting fire to the system.

My problem was less with the memset as such as more with the complete thoughtlessness and ignorance in putting it there. If you absolutely have to put something like that in there, at least comment the inherent dangers properly. If possible (not without C++11 support) also add compile time check.

This topic is closed to new replies.

Advertisement