Thrift-2029:Port C++ tests to Windows
Client: cpp
Patch: Ben Craig

Updates cpp tests to work with windows and c++11
diff --git a/lib/cpp/test/AllProtocolTests.tcc b/lib/cpp/test/AllProtocolTests.tcc
index 9155da8..7ccaef5 100644
--- a/lib/cpp/test/AllProtocolTests.tcc
+++ b/lib/cpp/test/AllProtocolTests.tcc
@@ -45,7 +45,7 @@
   Val out;
   GenericIO::read(protocol, out);
   if (out != val) {
-    snprintf(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName<Val>());
+    THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName<Val>());
     throw TException(errorMessage);
   }
 }
@@ -71,11 +71,11 @@
   protocol->readFieldBegin(name, fieldType, fieldId);
 
   if (fieldId != 15) {
-    snprintf(errorMessage, ERR_LEN, "Invalid ID (type: %s)", typeid(val).name());
+    THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid ID (type: %s)", typeid(val).name());
     throw TException(errorMessage);
   }
   if (fieldType != type) {
-    snprintf(errorMessage, ERR_LEN, "Invalid Field Type (type: %s)", typeid(val).name());
+    THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid Field Type (type: %s)", typeid(val).name());
     throw TException(errorMessage);
   }
 
@@ -83,7 +83,7 @@
   GenericIO::read(protocol, out);
 
   if (out != val) {
-    snprintf(errorMessage, ERR_LEN, "Invalid value read (type: %s)", typeid(val).name());
+    THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid value read (type: %s)", typeid(val).name());
     throw TException(errorMessage);
   }
 
@@ -143,8 +143,8 @@
     testNaked<TProto, int16_t>((int16_t)-1);
     testNaked<TProto, int16_t>((int16_t)-15000);
     testNaked<TProto, int16_t>((int16_t)-0x7fff);
-    testNaked<TProto, int16_t>(std::numeric_limits<int16_t>::min());
-    testNaked<TProto, int16_t>(std::numeric_limits<int16_t>::max());
+    testNaked<TProto, int16_t>((std::numeric_limits<int16_t>::min)());
+    testNaked<TProto, int16_t>((std::numeric_limits<int16_t>::max)());
 
     testField<TProto, T_I16, int16_t>((int16_t)0);
     testField<TProto, T_I16, int16_t>((int16_t)1);
@@ -165,8 +165,8 @@
     testNaked<TProto, int32_t>(-1);
     testNaked<TProto, int32_t>(-15000);
     testNaked<TProto, int32_t>(-0xffff);
-    testNaked<TProto, int32_t>(std::numeric_limits<int32_t>::min());
-    testNaked<TProto, int32_t>(std::numeric_limits<int32_t>::max());
+    testNaked<TProto, int32_t>((std::numeric_limits<int32_t>::min)());
+    testNaked<TProto, int32_t>((std::numeric_limits<int32_t>::max)());
 
     testField<TProto, T_I32, int32_t>(0);
     testField<TProto, T_I32, int32_t>(1);
@@ -182,12 +182,12 @@
     testField<TProto, T_I32, int32_t>(-15000);
     testField<TProto, T_I32, int32_t>(-0xffff);
     testField<TProto, T_I32, int32_t>(-0xffffff);
-    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::min());
-    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::max());
-    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::min() + 10);
-    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::max() - 16);
-    testNaked<TProto, int64_t>(std::numeric_limits<int64_t>::min());
-    testNaked<TProto, int64_t>(std::numeric_limits<int64_t>::max());
+    testNaked<TProto, int64_t>((std::numeric_limits<int32_t>::min)());
+    testNaked<TProto, int64_t>((std::numeric_limits<int32_t>::max)());
+    testNaked<TProto, int64_t>((std::numeric_limits<int32_t>::min)() + 10);
+    testNaked<TProto, int64_t>((std::numeric_limits<int32_t>::max)() - 16);
+    testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::min)());
+    testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::max)());
 
 
     testNaked<TProto, int64_t>(0);
@@ -219,7 +219,7 @@
 
     printf("%s => OK\n", protoname);
   } catch (TException e) {
-    snprintf(errorMessage, ERR_LEN, "%s => Test FAILED: %s", protoname, e.what());
+    THRIFT_SNPRINTF(errorMessage, ERR_LEN, "%s => Test FAILED: %s", protoname, e.what());
     throw TException(errorMessage);
   }
 }
diff --git a/lib/cpp/test/DebugProtoTest.cpp b/lib/cpp/test/DebugProtoTest.cpp
index 26cc1ea..5649e18 100644
--- a/lib/cpp/test/DebugProtoTest.cpp
+++ b/lib/cpp/test/DebugProtoTest.cpp
@@ -17,6 +17,7 @@
  * under the License.
  */
 
+#define _USE_MATH_DEFINES
 #include <iostream>
 #include <cmath>
 #include "gen-cpp/DebugProtoTest_types.h"
diff --git a/lib/cpp/test/JSONProtoTest.cpp b/lib/cpp/test/JSONProtoTest.cpp
index dcb34d1..be8f426 100644
--- a/lib/cpp/test/JSONProtoTest.cpp
+++ b/lib/cpp/test/JSONProtoTest.cpp
@@ -17,6 +17,7 @@
  * under the License.
  */
 
+#define _USE_MATH_DEFINES
 #include <iostream>
 #include <cmath>
 #include <thrift/transport/TBufferTransports.h>
diff --git a/lib/cpp/test/OptionalRequiredTest.cpp b/lib/cpp/test/OptionalRequiredTest.cpp
index ddafa81..44b6885 100644
--- a/lib/cpp/test/OptionalRequiredTest.cpp
+++ b/lib/cpp/test/OptionalRequiredTest.cpp
@@ -157,7 +157,7 @@
       write_to_read(t2, t3);
       abort();
     }
-    catch (TProtocolException& ex) {}
+    catch (const TProtocolException&) {}
 
     write_to_read(t3, t2);
     assert(t2.__isset.im_optional);
diff --git a/lib/cpp/test/SpecializationTest.cpp b/lib/cpp/test/SpecializationTest.cpp
index 7a3d347..0bef12a 100644
--- a/lib/cpp/test/SpecializationTest.cpp
+++ b/lib/cpp/test/SpecializationTest.cpp
@@ -1,3 +1,4 @@
+#define _USE_MATH_DEFINES
 #include <iostream>
 #include <cmath>
 #include <thrift/transport/TTransportUtils.h>
@@ -32,7 +33,7 @@
   n.my_ooe.integer16 = 16;
   n.my_ooe.integer32 = 32;
   n.my_ooe.integer64 = 64;
-  n.my_ooe.double_precision = (std::sqrt(5)+1)/2;
+  n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
   n.my_ooe.some_characters  = ":R (me going \"rrrr\")";
   n.my_ooe.zomg_unicode     = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
                               "\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
diff --git a/lib/cpp/test/TBufferBaseTest.cpp b/lib/cpp/test/TBufferBaseTest.cpp
index f88a019..5d0bf45 100644
--- a/lib/cpp/test/TBufferBaseTest.cpp
+++ b/lib/cpp/test/TBufferBaseTest.cpp
@@ -349,7 +349,7 @@
       int write_index = 0;
       unsigned int to_write = (1<<14)-42;
       while (to_write > 0) {
-        int write_amt = std::min(dist[d1][write_index], to_write);
+        int write_amt = (std::min)(dist[d1][write_index], to_write);
         buffer.write(&data[write_offset], write_amt);
         write_offset += write_amt;
         write_index++;
@@ -360,7 +360,7 @@
       int read_index = 0;
       unsigned int to_read = (1<<13)-42;
       while (to_read > 0) {
-        int read_amt = std::min(dist[d2][read_index], to_read);
+        int read_amt = (std::min)(dist[d2][read_index], to_read);
         int got = buffer.read(&data_out[read_offset], read_amt);
         BOOST_CHECK_EQUAL(got, read_amt);
         read_offset += read_amt;
@@ -374,7 +374,7 @@
       int second_index = write_index-1;
       unsigned int to_second = (1<<14)+42;
       while (to_second > 0) {
-        int second_amt = std::min(dist[d1][second_index], to_second);
+        int second_amt = (std::min)(dist[d1][second_index], to_second);
         //printf("%d\n", second_amt);
         buffer.write(&data[second_offset], second_amt);
         second_offset += second_amt;
diff --git a/lib/cpp/test/TMemoryBufferTest.cpp b/lib/cpp/test/TMemoryBufferTest.cpp
index 10b53f4..b81a667 100644
--- a/lib/cpp/test/TMemoryBufferTest.cpp
+++ b/lib/cpp/test/TMemoryBufferTest.cpp
@@ -46,7 +46,7 @@
     shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
     shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));
 
-    strBuffer2->resetBuffer((uint8_t*)serialized.data(), serialized.length());
+    strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
     thrift::test::Xtruct a2;
     a2.read(binaryProtcol2.get());
 
@@ -62,7 +62,7 @@
 
     string* str1 = new string("abcd1234");
     const char* data1 = str1->data();
-    TMemoryBuffer buf((uint8_t*)str1->data(), str1->length(), TMemoryBuffer::COPY);
+    TMemoryBuffer buf((uint8_t*)str1->data(), static_cast<uint32_t>(str1->length()), TMemoryBuffer::COPY);
     delete str1;
     string* str2 = new string("plsreuse");
     bool obj_reuse = (str1 == str2);
@@ -94,12 +94,12 @@
     try {
       buf1.write((const uint8_t*)"foo", 3);
       assert(false);
-    } catch (TTransportException& ex) {}
+    } catch (TTransportException&) {}
 
     TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
     try {
       buf2.write((const uint8_t*)"bar", 3);
-    } catch (TTransportException& ex) {
+    } catch (TTransportException&) {
       assert(false);
     }
   }
diff --git a/lib/cpp/test/TransportTest.cpp b/lib/cpp/test/TransportTest.cpp
index 4233e6e..78c2764 100755
--- a/lib/cpp/test/TransportTest.cpp
+++ b/lib/cpp/test/TransportTest.cpp
@@ -16,17 +16,11 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE // needed for getopt_long
-#endif
-
 #include <stdlib.h>
 #include <time.h>
-#include <unistd.h>
-#include <getopt.h>
-#include <signal.h>
 #include <sstream>
-#include <tr1/functional>
+#include <fstream>
+#include <thrift/cxxfunctional.h>
 
 #include <boost/mpl/list.hpp>
 #include <boost/shared_array.hpp>
@@ -40,10 +34,15 @@
 #include <thrift/transport/TZlibTransport.h>
 #include <thrift/transport/TSocket.h>
 
+#include <thrift/concurrency/FunctionRunner.h>
+#if _WIN32
+  #include <thrift/windows/TWinsockSingleton.h>
+#endif
+
+
 using namespace apache::thrift::transport;
 
 static boost::mt19937 rng;
-static const char* tmp_dir = "/tmp";
 
 void initrand(unsigned int seed) {
   rng.seed(seed);
@@ -83,8 +82,8 @@
     return desc.str();
   }
 
-  uint32_t getMin() const { return generator_.distribution().min(); }
-  uint32_t getMax() const { return generator_.distribution().max(); }
+  uint32_t getMin() const { return (generator_.distribution().min)(); }
+  uint32_t getMax() const { return (generator_.distribution().max)(); }
 
  private:
   boost::variate_generator< boost::mt19937&, boost::uniform_int<int> >
@@ -206,6 +205,8 @@
 typedef CoupledZlibTransportsT<CoupledMemoryBuffers>
   CoupledZlibTransports;
 
+#ifndef _WIN32
+// FD transport doesn't make much sense on Windows.
 /**
  * Coupled TFDTransports.
  */
@@ -222,6 +223,7 @@
     out.reset(new TFDTransport(pipes[1], TFDTransport::CLOSE_ON_DESTROY));
   }
 };
+#endif
 
 /**
  * Coupled TSockets
@@ -229,8 +231,8 @@
 class CoupledSocketTransports : public CoupledTransports<TSocket> {
  public:
   CoupledSocketTransports() {
-    int sockets[2];
-    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
+    THRIFT_SOCKET sockets[2] = {0};
+    if (THRIFT_SOCKETPAIR(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
       return;
     }
 
@@ -240,20 +242,30 @@
   }
 };
 
+//These could be made to work on Windows, but I don't care enough to make it happen
+#ifndef _WIN32
 /**
  * Coupled TFileTransports
  */
 class CoupledFileTransports : public CoupledTransports<TFileTransport> {
  public:
   CoupledFileTransports() {
+#ifndef _WIN32
+    const char* tmp_dir = "/tmp";
+    #define FILENAME_SUFFIX "/thrift.transport_test"
+#else
+    const char* tmp_dir = getenv("TMP");
+    #define FILENAME_SUFFIX "\\thrift.transport_test"
+#endif
+
     // Create a temporary file to use
-    size_t filename_len = strlen(tmp_dir) + 32;
-    filename = new char[filename_len];
-    snprintf(filename, filename_len,
-             "%s/thrift.transport_test.XXXXXX", tmp_dir);
-    fd = mkstemp(filename);
-    if (fd < 0) {
-      return;
+    filename.resize(strlen(tmp_dir) + strlen(FILENAME_SUFFIX));
+    THRIFT_SNPRINTF(&filename[0], filename.size(),
+             "%s" FILENAME_SUFFIX, tmp_dir);
+    #undef FILENAME_SUFFIX
+
+    {
+      std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc);
     }
 
     in.reset(new TFileTransport(filename, true));
@@ -261,16 +273,12 @@
   }
 
   ~CoupledFileTransports() {
-    if (fd >= 0) {
-      close(fd);
-      unlink(filename);
-    }
-    delete[] filename;
+    remove(filename.c_str());
   }
 
-  char* filename;
-  int fd;
+  std::string filename;
 };
+#endif
 
 /**
  * Wrapper around another CoupledTransports implementation that exposes the
@@ -337,31 +345,33 @@
   TriggerInfo* next;
 };
 
-TriggerInfo* triggerInfo;
-unsigned int numTriggersFired;
+apache::thrift::concurrency::Monitor g_alarm_monitor;
+TriggerInfo* g_triggerInfo;
+unsigned int g_numTriggersFired;
+bool g_teardown = false;
 
-void set_alarm();
+void alarm_handler() {
+  TriggerInfo *info = NULL;
+  {
+    apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
+    // The alarm timed out, which almost certainly means we're stuck
+    // on a transport that is incorrectly blocked.
+    ++g_numTriggersFired;
 
-void alarm_handler(int signum) {
-  (void) signum;
-  // The alarm timed out, which almost certainly means we're stuck
-  // on a transport that is incorrectly blocked.
-  ++numTriggersFired;
+    // Note: we print messages to stdout instead of stderr, since
+    // tools/test/runner only records stdout messages in the failure messages for
+    // boost tests.  (boost prints its test info to stdout.)
+    printf("Timeout alarm expired; attempting to unblock transport\n");
+    if (g_triggerInfo == NULL) {
+      printf("  trigger stack is empty!\n");
+    }
 
-  // Note: we print messages to stdout instead of stderr, since
-  // tools/test/runner only records stdout messages in the failure messages for
-  // boost tests.  (boost prints its test info to stdout.)
-  printf("Timeout alarm expired; attempting to unblock transport\n");
-  if (triggerInfo == NULL) {
-    printf("  trigger stack is empty!\n");
+    // Pop off the first TriggerInfo.
+    // If there is another one, schedule an alarm for it.
+    info = g_triggerInfo;
+    g_triggerInfo = info->next;
   }
 
-  // Pop off the first TriggerInfo.
-  // If there is another one, schedule an alarm for it.
-  TriggerInfo* info = triggerInfo;
-  triggerInfo = info->next;
-  set_alarm();
-
   // Write some data to the transport to hopefully unblock it.
   uint8_t* buf = new uint8_t[info->writeLength];
   memset(buf, 'b', info->writeLength);
@@ -372,21 +382,28 @@
   delete info;
 }
 
-void set_alarm() {
-  if (triggerInfo == NULL) {
-    // clear any alarm
-    alarm(0);
-    return;
+void alarm_handler_wrapper() {
+  int64_t timeout = 0;  //timeout of 0 means wait forever
+  while(true) {
+    bool fireHandler = false;
+    {
+      apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
+      if(g_teardown)
+         return;
+      //calculate timeout
+      if (g_triggerInfo == NULL) {
+        timeout = 0;
+      } else {
+         timeout = g_triggerInfo->timeoutSeconds * 1000;
+      }
+
+      int waitResult = g_alarm_monitor.waitForTimeRelative(timeout);
+      if(waitResult == THRIFT_ETIMEDOUT)
+        fireHandler = true;
+    }
+    if(fireHandler)
+      alarm_handler(); //calling outside the lock
   }
-
-  struct sigaction action;
-  memset(&action, 0, sizeof(action));
-  action.sa_handler = alarm_handler;
-  action.sa_flags = SA_RESETHAND;
-  sigemptyset(&action.sa_mask);
-  sigaction(SIGALRM, &action, NULL);
-
-  alarm(triggerInfo->timeoutSeconds);
 }
 
 /**
@@ -401,28 +418,34 @@
                  const boost::shared_ptr<TTransport> &transport,
                  uint32_t write_len) {
   TriggerInfo* info = new TriggerInfo(seconds, transport, write_len);
-
-  if (triggerInfo == NULL) {
-    // This is the first trigger.
-    // Set triggerInfo, and schedule the alarm
-    triggerInfo = info;
-    set_alarm();
-  } else {
-    // Add this trigger to the end of the list
-    TriggerInfo* prev = triggerInfo;
-    while (prev->next) {
-      prev = prev->next;
+  {
+    apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
+    if (g_triggerInfo == NULL) {
+      // This is the first trigger.
+      // Set g_triggerInfo, and schedule the alarm
+      g_triggerInfo = info;
+      g_alarm_monitor.notify();
+    } else {
+      // Add this trigger to the end of the list
+      TriggerInfo* prev = g_triggerInfo;
+      while (prev->next) {
+        prev = prev->next;
+      }
+      prev->next = info;
     }
-
-    prev->next = info;
   }
 }
 
 void clear_triggers() {
-  TriggerInfo *info = triggerInfo;
-  alarm(0);
-  triggerInfo = NULL;
-  numTriggersFired = 0;
+  TriggerInfo *info = NULL;
+
+  {
+    apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
+    info = g_triggerInfo;
+    g_triggerInfo = NULL;
+    g_numTriggersFired = 0;
+    g_alarm_monitor.notify();
+  }
 
   while (info != NULL) {
     TriggerInfo* next = info->next;
@@ -586,7 +609,7 @@
   transports.out->flush();
   set_trigger(3, transports.out, 1);
   uint32_t bytes_read = transports.in->read(read_buf, 10);
-  BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0);
+  BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
   BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 9);
 
   clear_triggers();
@@ -608,13 +631,13 @@
 
   // Read 1 byte, to force the transport to read the frame
   uint32_t bytes_read = transports.in->read(read_buf, 1);
-  BOOST_CHECK_EQUAL(bytes_read, 1);
+  BOOST_CHECK_EQUAL(bytes_read, 1u);
 
   // Read more than what is remaining and verify the transport does not block
   set_trigger(3, transports.out, 1);
   bytes_read = transports.in->read(read_buf, 10);
-  BOOST_CHECK_EQUAL(numTriggersFired, 0);
-  BOOST_CHECK_EQUAL(bytes_read, 9);
+  BOOST_CHECK_EQUAL(g_numTriggersFired, 0u);
+  BOOST_CHECK_EQUAL(bytes_read, 9u);
 
   clear_triggers();
 }
@@ -666,7 +689,7 @@
   while (total_read < 9) {
     set_trigger(3, transports.out, 1);
     bytes_read = transports.in->read(read_buf, 10);
-    BOOST_REQUIRE_EQUAL(numTriggersFired, (unsigned int) 0);
+    BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int) 0);
     BOOST_REQUIRE_GT(bytes_read, (uint32_t) 0);
     total_read += bytes_read;
     BOOST_REQUIRE_LE(total_read, (uint32_t) 9);
@@ -694,7 +717,7 @@
   set_trigger(3, transports.out, 1);
   uint32_t borrow_len = 10;
   const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len);
-  BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0);
+  BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
   BOOST_CHECK(borrowed_buf == NULL);
 
   clear_triggers();
@@ -720,10 +743,10 @@
   add_trigger(1, transports.out, 8);
   uint32_t bytes_read = transports.in->read(read_buf, 10);
   if (bytes_read == 0) {
-    BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0);
+    BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
     clear_triggers();
   } else {
-    BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 1);
+    BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 1);
     BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 2);
   }
 
@@ -744,7 +767,7 @@
   uint32_t borrow_len = 10;
   const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len);
   BOOST_CHECK(borrowed_buf == NULL);
-  BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0);
+  BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
 
   clear_triggers();
 }
@@ -828,6 +851,7 @@
 
     TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers);
 
+#ifndef _WIN32
     // TFDTransport tests
     // Since CoupledFDTransports tests with a pipe, writes will block
     // if there is too much outstanding unread data in the pipe.
@@ -851,6 +875,7 @@
             rand4k, rand4k, fd_max_outstanding);
 
     TEST_BLOCKING_BEHAVIOR(CoupledFDTransports);
+#endif //_WIN32
 
     // TSocket tests
     uint32_t socket_max_outstanding = 4096;
@@ -876,6 +901,8 @@
 
     TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports);
 
+//These could be made to work on Windows, but I don't care enough to make it happen
+#ifndef _WIN32
     // TFileTransport tests
     // We use smaller buffer sizes here, since TFileTransport is fairly slow.
     //
@@ -893,6 +920,7 @@
     TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k);
 
     TEST_BLOCKING_BEHAVIOR(CoupledFileTransports);
+#endif
 
     // Add some tests that access TBufferedTransport and TFramedTransport
     // via TTransport pointers and TBufferBase pointers.
@@ -928,7 +956,7 @@
       maxOutstanding << ")";
 
     boost::unit_test::callback0<> test_func =
-      std::tr1::bind(test_rw<CoupledTransports>, totalSize,
+      apache::thrift::stdcxx::bind(test_rw<CoupledTransports>, totalSize,
                      wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen,
                      maxOutstanding);
     boost::unit_test::test_case* tc =
@@ -942,37 +970,37 @@
     char name[1024];
     boost::unit_test::test_case* tc;
 
-    snprintf(name, sizeof(name), "%s::test_read_part_available()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_read_part_available<CoupledTransports>, name);
     suite_->add(tc, expectedFailures);
 
-    snprintf(name, sizeof(name), "%s::test_read_part_available_in_chunks()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_read_part_available_in_chunks<CoupledTransports>, name);
     suite_->add(tc, expectedFailures);
 
-    snprintf(name, sizeof(name), "%s::test_read_partial_midframe()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_read_partial_midframe<CoupledTransports>, name);
     suite_->add(tc, expectedFailures);
 
-    snprintf(name, sizeof(name), "%s::test_read_none_available()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_read_none_available<CoupledTransports>, name);
     suite_->add(tc, expectedFailures);
 
-    snprintf(name, sizeof(name), "%s::test_borrow_part_available()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_borrow_part_available<CoupledTransports>, name);
     suite_->add(tc, expectedFailures);
 
-    snprintf(name, sizeof(name), "%s::test_borrow_none_available()",
+    THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()",
              transportName);
     tc = boost::unit_test::make_test_case(
           test_borrow_none_available<CoupledTransports>, name);
@@ -991,103 +1019,43 @@
  * General Initialization
  **************************************************************************/
 
-void print_usage(FILE* f, const char* argv0) {
-  fprintf(f, "Usage: %s [boost_options] [options]\n", argv0);
-  fprintf(f, "Options:\n");
-  fprintf(f, "  --seed=<N>, -s <N>\n");
-  fprintf(f, "  --tmp-dir=DIR, -t DIR\n");
-  fprintf(f, "  --help\n");
-}
+struct global_fixture {
+  boost::shared_ptr<apache::thrift::concurrency::Thread> alarmThread_;
+  global_fixture() {
+  #if _WIN32
+    apache::thrift::transport::TWinsockSingleton::create();
+  #endif
 
-struct Options {
-  int seed;
-  bool haveSeed;
-  float sizeMultiplier;
+    apache::thrift::concurrency::PlatformThreadFactory factory;
+    factory.setDetached(false);
+
+    alarmThread_ = factory.newThread(
+      apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper));
+    alarmThread_->start();
+  }
+  ~global_fixture() {
+    {
+      apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
+      g_teardown = true;
+      g_alarm_monitor.notify();
+    }
+    alarmThread_->join();
+  }
 };
 
-void parse_args(int argc, char* argv[], Options* options) {
-  bool have_seed = false;
-  options->sizeMultiplier = 1;
-
-  struct option long_opts[] = {
-    { "help", false, NULL, 'h' },
-    { "seed", true, NULL, 's' },
-    { "tmp-dir", true, NULL, 't' },
-    { "size-multiplier", true, NULL, 'x' },
-    { NULL, 0, NULL, 0 }
-  };
-
-  while (true) {
-    optopt = 1;
-    int optchar = getopt_long(argc, argv, "hs:t:x:", long_opts, NULL);
-    if (optchar == -1) {
-      break;
-    }
-
-    switch (optchar) {
-      case 't':
-        tmp_dir = optarg;
-        break;
-      case 's': {
-        char *endptr;
-        options->seed = strtol(optarg, &endptr, 0);
-        if (endptr == optarg || *endptr != '\0') {
-          fprintf(stderr, "invalid seed value \"%s\": must be an integer\n",
-                  optarg);
-          exit(1);
-        }
-        have_seed = true;
-        break;
-      }
-      case 'h':
-        print_usage(stdout, argv[0]);
-        exit(0);
-      case 'x': {
-        char *endptr;
-        options->sizeMultiplier = strtof(optarg, &endptr);
-        if (endptr == optarg || *endptr != '\0') {
-          fprintf(stderr, "invalid size multiplier \"%s\": must be a number\n",
-                  optarg);
-          exit(1);
-        }
-        if (options->sizeMultiplier < 0) {
-          fprintf(stderr, "invalid size multiplier \"%s\": "
-                  "must be non-negative\n", optarg);
-          exit(1);
-        }
-        break;
-      }
-      case '?':
-        exit(1);
-      default:
-        // Only happens if someone adds another option to the optarg string,
-        // but doesn't update the switch statement to handle it.
-        fprintf(stderr, "unknown option \"-%c\"\n", optchar);
-        exit(1);
-    }
-  }
-
-  if (!have_seed) {
-    // choose a seed now if the user didn't specify one
-    struct timeval tv;
-    struct timezone tz;
-    gettimeofday(&tv, &tz);
-    options->seed = tv.tv_sec ^ tv.tv_usec;
-  }
-}
+BOOST_GLOBAL_FIXTURE(global_fixture)
 
 boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
-  // Parse arguments
-  Options options;
-  parse_args(argc, argv, &options);
+  struct timeval tv;
+  THRIFT_GETTIMEOFDAY(&tv, NULL);
+  int seed = tv.tv_sec ^ tv.tv_usec;
 
-  initrand(options.seed);
+  initrand(seed);
 
   boost::unit_test::test_suite* suite =
     &boost::unit_test::framework::master_test_suite();
   suite->p_name.value = "TransportTest";
-  TransportTestGen transport_test_generator(suite, options.sizeMultiplier);
+  TransportTestGen transport_test_generator(suite, 1);
   transport_test_generator.generate();
-
   return NULL;
 }
diff --git a/lib/cpp/test/ZlibTest.cpp b/lib/cpp/test/ZlibTest.cpp
index 4d7966e..1e8b646 100644
--- a/lib/cpp/test/ZlibTest.cpp
+++ b/lib/cpp/test/ZlibTest.cpp
@@ -26,11 +26,10 @@
 
 #include <stdint.h>
 #include <inttypes.h>
-#include <getopt.h>
 #include <cstddef>
 #include <fstream>
 #include <iostream>
-#include <tr1/functional>
+#include <thrift/cxxfunctional.h>
 
 #include <boost/random.hpp>
 #include <boost/shared_array.hpp>
@@ -40,7 +39,6 @@
 #include <thrift/transport/TZlibTransport.h>
 
 using namespace std;
-using namespace boost;
 using namespace apache::thrift::transport;
 
 boost::mt19937 rng;
@@ -69,7 +67,7 @@
 class LogNormalSizeGenerator : public SizeGenerator {
  public:
   LogNormalSizeGenerator(double mean, double std_dev) :
-      gen_(rng, lognormal_distribution<double>(mean, std_dev)) {}
+      gen_(rng, boost::lognormal_distribution<double>(mean, std_dev)) {}
 
   virtual unsigned int getSize() {
     // Loop until we get a size of 1 or more
@@ -82,7 +80,7 @@
   }
 
  private:
-  variate_generator< mt19937, lognormal_distribution<double> > gen_;
+  boost::variate_generator< boost::mt19937, boost::lognormal_distribution<double> > gen_;
 };
 
 uint8_t* gen_uniform_buffer(uint32_t buf_len, uint8_t c) {
@@ -169,7 +167,7 @@
   membuf->appendBufferToString(tmp_buf);
   zlib_trans.reset(new TZlibTransport(membuf,
                                       TZlibTransport::DEFAULT_URBUF_SIZE,
-                                      tmp_buf.length()-1));
+                                      static_cast<uint32_t>(tmp_buf.length()-1)));
 
   boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
   uint32_t got = zlib_trans->readAll(mirror.get(), buf_len);
@@ -190,7 +188,7 @@
   tmp_buf.erase(tmp_buf.length() - 1);
   membuf->resetBuffer(const_cast<uint8_t*>(
                         reinterpret_cast<const uint8_t*>(tmp_buf.data())),
-                      tmp_buf.length());
+                      static_cast<uint32_t>(tmp_buf.length()));
 
   boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
   uint32_t got = zlib_trans->readAll(mirror.get(), buf_len);
@@ -264,11 +262,11 @@
   // (When this occurs, verifyChecksum() throws an exception indicating
   // that the end of the data hasn't been reached.)  I haven't seen this
   // error when only modifying checksum bytes.
-  int index = tmp_buf.size() - 1;
+  int index = static_cast<int>(tmp_buf.size() - 1);
   tmp_buf[index]++;
   membuf->resetBuffer(const_cast<uint8_t*>(
                         reinterpret_cast<const uint8_t*>(tmp_buf.data())),
-                      tmp_buf.length());
+                      static_cast<uint32_t>(tmp_buf.length()));
 
   boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
   try {
@@ -337,12 +335,12 @@
     ::std::ostringstream name_ss; \
     name_ss << name << "-" << BOOST_STRINGIZE(function); \
     ::boost::unit_test::test_case* tc = ::boost::unit_test::make_test_case( \
-        ::std::tr1::bind(function, ## __VA_ARGS__), \
+        ::apache::thrift::stdcxx::bind(function, ## __VA_ARGS__), \
         name_ss.str()); \
     (suite)->add(tc); \
   } while (0)
 
-void add_tests(unit_test::test_suite* suite,
+void add_tests(boost::unit_test::test_suite* suite,
                const uint8_t* buf,
                uint32_t buf_len,
                const char* name) {
@@ -387,60 +385,12 @@
   fprintf(f, "  --help\n");
 }
 
-void parse_args(int argc, char* argv[]) {
-  uint32_t seed = 0;
-  bool has_seed = false;
-
-  struct option long_opts[] = {
-    { "help", false, NULL, 'h' },
-    { "seed", true, NULL, 's' },
-    { NULL, 0, NULL, 0 }
-  };
-
-  while (true) {
-    optopt = 1;
-    int optchar = getopt_long(argc, argv, "hs:", long_opts, NULL);
-    if (optchar == -1) {
-      break;
-    }
-
-    switch (optchar) {
-      case 's': {
-        char *endptr;
-        seed = strtol(optarg, &endptr, 0);
-        if (endptr == optarg || *endptr != '\0') {
-          fprintf(stderr, "invalid seed value \"%s\": must be a positive "
-                  "integer\n", optarg);
-          exit(1);
-        }
-        has_seed = true;
-        break;
-      }
-      case 'h':
-        print_usage(stdout, argv[0]);
-        exit(0);
-      case '?':
-        exit(1);
-      default:
-        // Only happens if someone adds another option to the optarg string,
-        // but doesn't update the switch statement to handle it.
-        fprintf(stderr, "unknown option \"-%c\"\n", optchar);
-        exit(1);
-    }
-  }
-
-  if (!has_seed) {
-    seed = time(NULL);
-  }
-
+boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
+  uint32_t seed = static_cast<uint32_t>(time(NULL));
   printf("seed: %" PRIu32 "\n", seed);
   rng.seed(seed);
-}
 
-unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
-  parse_args(argc, argv);
-
-  unit_test::test_suite* suite =
+  boost::unit_test::test_suite* suite =
     &boost::unit_test::framework::master_test_suite();
   suite->p_name.value = "ZlibTest";
 
diff --git a/test/cpp/src/StressTest.cpp b/test/cpp/src/StressTest.cpp
index 7da3db0..dfe8350 100644
--- a/test/cpp/src/StressTest.cpp
+++ b/test/cpp/src/StressTest.cpp
@@ -39,9 +39,11 @@
 #include <stdexcept>
 #include <sstream>
 #include <map>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 using namespace std;
-using namespace boost;
 
 using namespace apache::thrift;
 using namespace apache::thrift::protocol;
@@ -169,6 +171,7 @@
       int8_t arg = 1;
       int8_t result;
       result =_client->echoByte(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -178,6 +181,7 @@
       int32_t arg = 1;
       int32_t result;
       result =_client->echoI32(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -187,6 +191,7 @@
       int64_t arg = 1;
       int64_t result;
       result =_client->echoI64(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -212,8 +217,31 @@
   Monitor _sleep;
 };
 
+class TStartObserver : public apache::thrift::server::TServerEventHandler
+{
+public:
+   TStartObserver() : awake_(false) {}
+   virtual void preServe()
+   {
+      apache::thrift::concurrency::Synchronized s(m_);
+      awake_ = true;
+      m_.notifyAll();
+   }
+   void waitForService()
+   {
+      apache::thrift::concurrency::Synchronized s(m_);
+      while(!awake_)
+         m_.waitForever();
+   }
+ private:
+   apache::thrift::concurrency::Monitor m_;
+   bool awake_;
+};
 
 int main(int argc, char **argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
 
   int port = 9091;
   string serverType = "thread-pool";
@@ -323,7 +351,7 @@
 
   } catch(std::exception& e) {
     cerr << e.what() << endl;
-    cerr << usage;
+    cerr << usage.str();
   }
 
   boost::shared_ptr<PlatformThreadFactory> threadFactory = boost::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
@@ -376,15 +404,15 @@
         boost::shared_ptr<TTransportFactory>(new TPipedTransportFactory(fileTransport));
     }
 
-    boost::shared_ptr<Thread> serverThread;
+    boost::shared_ptr<TServer> server;
 
     if (serverType == "simple") {
 
-      serverThread = threadFactory->newThread(boost::shared_ptr<TServer>(new TSimpleServer(serviceProcessor, serverSocket, transportFactory, protocolFactory)));
+      server.reset(new TSimpleServer(serviceProcessor, serverSocket, transportFactory, protocolFactory));
 
     } else if (serverType == "threaded") {
 
-      serverThread = threadFactory->newThread(boost::shared_ptr<TServer>(new TThreadedServer(serviceProcessor, serverSocket, transportFactory, protocolFactory)));
+      server.reset(new TThreadedServer(serviceProcessor, serverSocket, transportFactory, protocolFactory));
 
     } else if (serverType == "thread-pool") {
 
@@ -392,15 +420,19 @@
 
       threadManager->threadFactory(threadFactory);
       threadManager->start();
-      serverThread = threadFactory->newThread(boost::shared_ptr<TServer>(new TThreadPoolServer(serviceProcessor, serverSocket, transportFactory, protocolFactory, threadManager)));
+      server.reset(new TThreadPoolServer(serviceProcessor, serverSocket, transportFactory, protocolFactory, threadManager));
     }
 
+    boost::shared_ptr<TStartObserver> observer(new TStartObserver);
+    server->setServerEventHandler(observer);
+    boost::shared_ptr<Thread> serverThread = threadFactory->newThread(server);
+
     cerr << "Starting the server on port " << port << endl;
 
     serverThread->start();
+    observer->waitForService();
 
     // If we aren't running clients, just wait forever for external clients
-
     if (clientCount == 0) {
       serverThread->join();
     }
@@ -463,7 +495,7 @@
 
     for (set<boost::shared_ptr<Thread> >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) {
 
-      boost::shared_ptr<ClientThread> client = dynamic_pointer_cast<ClientThread>((*ix)->runnable());
+      boost::shared_ptr<ClientThread> client = boost::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
 
       int64_t delta = client->_endTime - client->_startTime;
 
diff --git a/test/cpp/src/StressTestNonBlocking.cpp b/test/cpp/src/StressTestNonBlocking.cpp
index c230c84..20320c7 100644
--- a/test/cpp/src/StressTestNonBlocking.cpp
+++ b/test/cpp/src/StressTestNonBlocking.cpp
@@ -35,7 +35,6 @@
 
 #include "Service.h"
 
-#include <unistd.h>
 #include <boost/shared_ptr.hpp>
 
 #include <iostream>
@@ -43,9 +42,11 @@
 #include <stdexcept>
 #include <sstream>
 #include <map>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 using namespace std;
-using namespace boost;
 
 using namespace apache::thrift;
 using namespace apache::thrift::protocol;
@@ -84,7 +85,7 @@
   void echoVoid() {
     count("echoVoid");
     // Sleep to simulate work
-    usleep(5000);
+    THRIFT_SLEEP_USEC(1);
     return;
   }
 
@@ -175,6 +176,7 @@
       int8_t arg = 1;
       int8_t result;
       result =_client->echoByte(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -184,6 +186,7 @@
       int32_t arg = 1;
       int32_t result;
       result =_client->echoI32(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -193,6 +196,7 @@
       int64_t arg = 1;
       int64_t result;
       result =_client->echoI64(arg);
+      (void)result;
       assert(result == arg);
     }
   }
@@ -220,13 +224,16 @@
 
 
 int main(int argc, char **argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
 
   int port = 9091;
   string serverType = "simple";
   string protocolType = "binary";
-  size_t workerCount = 4;
-  size_t clientCount = 20;
-  size_t loopCount = 50000;
+  uint32_t workerCount = 4;
+  uint32_t clientCount = 20;
+  uint32_t loopCount = 1000;
   TType loopType  = T_VOID;
   string callName = "echoVoid";
   bool runServer = true;
@@ -318,7 +325,7 @@
 
   } catch(std::exception& e) {
     cerr << e.what() << endl;
-    cerr << usage;
+    cerr << usage.str();
   }
 
   boost::shared_ptr<PlatformThreadFactory> threadFactory = boost::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
@@ -397,7 +404,7 @@
       serverThread2->join();
     }
   }
-  sleep(1);
+  THRIFT_SLEEP_SEC(1);
 
   if (clientCount > 0) {
 
@@ -414,7 +421,7 @@
     else if (callName == "echoString") { loopType = T_STRING;}
     else {throw invalid_argument("Unknown service call "+callName);}
 
-    for (size_t ix = 0; ix < clientCount; ix++) {
+    for (uint32_t ix = 0; ix < clientCount; ix++) {
 
       boost::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port + (ix % 2)));
       boost::shared_ptr<TFramedTransport> framedSocket(new TFramedTransport(socket));
@@ -456,7 +463,7 @@
 
     for (set<boost::shared_ptr<Thread> >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) {
 
-      boost::shared_ptr<ClientThread> client = dynamic_pointer_cast<ClientThread>((*ix)->runnable());
+      boost::shared_ptr<ClientThread> client = boost::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
 
       int64_t delta = client->_endTime - client->_startTime;
 
diff --git a/test/cpp/src/TestClient.cpp b/test/cpp/src/TestClient.cpp
index fbf04f0..cd78505 100644
--- a/test/cpp/src/TestClient.cpp
+++ b/test/cpp/src/TestClient.cpp
@@ -21,8 +21,6 @@
 #include <inttypes.h>
 
 #include <iostream>
-#include <unistd.h>
-#include <sys/time.h>
 #include <thrift/protocol/TBinaryProtocol.h>
 #include <thrift/protocol/TJSONProtocol.h>
 #include <thrift/transport/THttpClient.h>
@@ -34,11 +32,13 @@
 
 #include <boost/shared_ptr.hpp>
 #include <boost/program_options.hpp>
-#include <tr1/functional>
+#include <thrift/cxxfunctional.h>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 #include "ThriftTest.h"
 
-using namespace boost;
 using namespace std;
 using namespace apache::thrift;
 using namespace apache::thrift::protocol;
@@ -54,7 +54,7 @@
   int64_t ret;
   struct timeval tv;
 
-  gettimeofday(&tv, NULL);
+  THRIFT_GETTIMEOFDAY(&tv, NULL);
   ret = tv.tv_sec;
   ret = ret*1000*1000 + tv.tv_usec;
   return ret;
@@ -69,7 +69,7 @@
     client->recv_testString(s);
     cout << "testString: " << s << endl;
   } catch (TException& exn) {
-    cout << "Error: " << exn.what() << endl;    
+    cout << "Error: " << exn.what() << endl;
   }
 
   event_base_loopbreak(base); // end test
@@ -86,11 +86,14 @@
     client = new ThriftTestCobClient(channel, protocolFactory);
     client->testString(tr1::bind(testString_clientReturn, host, port, base, protocolFactory, std::tr1::placeholders::_1), "Test");
   } catch (TException& exn) {
-    cout << "Error: " << exn.what() << endl;    
+    cout << "Error: " << exn.what() << endl;
   }
 }
 
 int main(int argc, char** argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
   string host = "localhost";
   int port = 9090;
   int numTests = 1;
@@ -99,28 +102,28 @@
   string protocol_type = "binary";
   string domain_socket = "";
 
-  program_options::options_description desc("Allowed options");
+  boost::program_options::options_description desc("Allowed options");
   desc.add_options()
       ("help,h", "produce help message")
-      ("host", program_options::value<string>(&host)->default_value(host), "Host to connect")
-      ("port", program_options::value<int>(&port)->default_value(port), "Port number to connect")
-	  ("domain-socket", program_options::value<string>(&domain_socket)->default_value(domain_socket), "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port")
-      ("transport", program_options::value<string>(&transport_type)->default_value(transport_type), "Transport: buffered, framed, http, evhttp")
-      ("protocol", program_options::value<string>(&protocol_type)->default_value(protocol_type), "Protocol: binary, json")
+      ("host", boost::program_options::value<string>(&host)->default_value(host), "Host to connect")
+      ("port", boost::program_options::value<int>(&port)->default_value(port), "Port number to connect")
+	  ("domain-socket", boost::program_options::value<string>(&domain_socket)->default_value(domain_socket), "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port")
+      ("transport", boost::program_options::value<string>(&transport_type)->default_value(transport_type), "Transport: buffered, framed, http, evhttp")
+      ("protocol", boost::program_options::value<string>(&protocol_type)->default_value(protocol_type), "Protocol: binary, json")
 	  ("ssl", "Encrypted Transport using SSL")
-      ("testloops,n", program_options::value<int>(&numTests)->default_value(numTests), "Number of Tests")
+      ("testloops,n", boost::program_options::value<int>(&numTests)->default_value(numTests), "Number of Tests")
   ;
 
-  program_options::variables_map vm;
-  program_options::store(program_options::parse_command_line(argc, argv, desc), vm);
-  program_options::notify(vm);    
+  boost::program_options::variables_map vm;
+  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
+  boost::program_options::notify(vm);
 
   if (vm.count("help")) {
     cout << desc << "\n";
     return 1;
   }
 
-  try {   
+  try {
     if (!protocol_type.empty()) {
       if (protocol_type == "binary") {
       } else if (protocol_type == "json") {
@@ -210,7 +213,7 @@
     boost::shared_ptr<TAsyncChannel> channel(new TEvhttpClientChannel(host.c_str(), "/", host.c_str(), port, base));
     ThriftTestCobClient* client = new ThriftTestCobClient(channel, protocolFactory.get());
     client->testVoid(tr1::bind(testVoid_clientReturn, host.c_str(), port, base, protocolFactory.get(), std::tr1::placeholders::_1));
-    
+
     event_base_loop(base, 0);
     return 0;
   }
@@ -574,7 +577,7 @@
         printf("  void\nFAILURE\n");
         failCount++;
 
-      } catch(TException& e) {
+      } catch(const TException&) {
         printf("  Caught TException\n");
       }
 
@@ -622,9 +625,9 @@
 
     /* test oneway void */
     {
-        printf("testClient.testOneway(3) =>");
+        printf("testClient.testOneway(1) =>");
         uint64_t startOneway = now();
-        testClient.testOneway(3);
+        testClient.testOneway(1);
         uint64_t elapsed = now() - startOneway;
         if (elapsed > 200 * 1000) { // 0.2 seconds
             printf("  FAILURE - took %.2f ms\n", (double)elapsed/1000.0);
diff --git a/test/cpp/src/TestServer.cpp b/test/cpp/src/TestServer.cpp
index c99fbac..adb8fd1 100644
--- a/test/cpp/src/TestServer.cpp
+++ b/test/cpp/src/TestServer.cpp
@@ -46,9 +46,11 @@
 #include <boost/program_options.hpp>
 
 #include <signal.h>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 using namespace std;
-using namespace boost;
 
 using namespace apache::thrift;
 using namespace apache::thrift::concurrency;
@@ -266,7 +268,7 @@
     (void) arg3;
     (void) arg4;
     (void) arg5;
-    
+
     printf("testMulti()\n");
 
     hello.string_thing = "Hello2";
@@ -314,9 +316,9 @@
     }
   }
 
-  void testOneway(int sleepFor) {
+  void testOneway(const int32_t sleepFor) {
     printf("testOneway(%d): Sleeping...\n", sleepFor);
-    sleep(sleepFor);
+    THRIFT_SLEEP_SEC(sleepFor);
     printf("testOneway(%d): done sleeping!\n", sleepFor);
   }
 };
@@ -447,7 +449,7 @@
   }
 
   virtual void testInsanity(std::tr1::function<void(std::map<UserId, std::map<Numberz::type, Insanity> >  const& _return)> cob, const Insanity& argument) {
-    std::map<UserId, std::map<Numberz::type, Insanity> > res; 
+    std::map<UserId, std::map<Numberz::type, Insanity> > res;
     _delegate->testInsanity(res, argument);
     cob(res);
  }
@@ -490,6 +492,9 @@
 
 
 int main(int argc, char **argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
   int port = 9090;
   bool ssl = false;
   string transport_type = "buffered";
@@ -498,34 +503,34 @@
   string domain_socket = "";
   size_t workers = 4;
 
- 
-  program_options::options_description desc("Allowed options");
+
+  boost::program_options::options_description desc("Allowed options");
   desc.add_options()
       ("help,h", "produce help message")
-      ("port", program_options::value<int>(&port)->default_value(port), "Port number to listen")
-	  ("domain-socket", program_options::value<string>(&domain_socket)->default_value(domain_socket),
+      ("port", boost::program_options::value<int>(&port)->default_value(port), "Port number to listen")
+	  ("domain-socket", boost::program_options::value<string>(&domain_socket)->default_value(domain_socket),
 	    "Unix Domain Socket (e.g. /tmp/ThriftTest.thrift)")
-      ("server-type", program_options::value<string>(&server_type)->default_value(server_type),
+      ("server-type", boost::program_options::value<string>(&server_type)->default_value(server_type),
         "type of server, \"simple\", \"thread-pool\", \"threaded\", or \"nonblocking\"")
-      ("transport", program_options::value<string>(&transport_type)->default_value(transport_type),
+      ("transport", boost::program_options::value<string>(&transport_type)->default_value(transport_type),
         "transport: buffered, framed, http")
-      ("protocol", program_options::value<string>(&protocol_type)->default_value(protocol_type),
+      ("protocol", boost::program_options::value<string>(&protocol_type)->default_value(protocol_type),
         "protocol: binary, json")
 	  ("ssl", "Encrypted Transport using SSL")
 	  ("processor-events", "processor-events")
-      ("workers,n", program_options::value<size_t>(&workers)->default_value(workers),
+      ("workers,n", boost::program_options::value<size_t>(&workers)->default_value(workers),
         "Number of thread pools workers. Only valid for thread-pool server type")
   ;
 
-  program_options::variables_map vm;
-  program_options::store(program_options::parse_command_line(argc, argv, desc), vm);
-  program_options::notify(vm);    
+  boost::program_options::variables_map vm;
+  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
+  boost::program_options::notify(vm);
 
   if (vm.count("help")) {
       cout << desc << "\n";
       return 1;
   }
-  
+
   try {
     if (!server_type.empty()) {
       if (server_type == "simple") {
@@ -536,7 +541,7 @@
           throw invalid_argument("Unknown server type "+server_type);
       }
     }
-    
+
     if (!protocol_type.empty()) {
       if (protocol_type == "binary") {
       } else if (protocol_type == "json") {
@@ -562,7 +567,6 @@
 
   if (vm.count("ssl")) {
     ssl = true;
-    signal(SIGPIPE, SIG_IGN);
   }
 
   // Dispatcher
@@ -578,12 +582,12 @@
   // Processor
   boost::shared_ptr<TestHandler> testHandler(new TestHandler());
   boost::shared_ptr<ThriftTestProcessor> testProcessor(new ThriftTestProcessor(testHandler));
-  
+
   if (vm.count("processor-events")) {
     testProcessor->setEventHandler(boost::shared_ptr<TProcessorEventHandler>(
           new TestProcessorEventHandler()));
   }
-  
+
   // Transport
   boost::shared_ptr<TSSLSocketFactory> sslSocketFactory;
   boost::shared_ptr<TServerSocket> serverSocket;
@@ -607,15 +611,15 @@
 
   // Factory
   boost::shared_ptr<TTransportFactory> transportFactory;
-  
+
   if (transport_type == "http" && server_type != "nonblocking") {
-    boost::shared_ptr<TTransportFactory> httpTransportFactory(new THttpServerTransportFactory()); 
+    boost::shared_ptr<TTransportFactory> httpTransportFactory(new THttpServerTransportFactory());
     transportFactory = httpTransportFactory;
   } else if (transport_type == "framed") {
-    boost::shared_ptr<TTransportFactory> framedTransportFactory(new TFramedTransportFactory()); 
+    boost::shared_ptr<TTransportFactory> framedTransportFactory(new TFramedTransportFactory());
     transportFactory = framedTransportFactory;
   } else {
-    boost::shared_ptr<TTransportFactory> bufferedTransportFactory(new TBufferedTransportFactory()); 
+    boost::shared_ptr<TTransportFactory> bufferedTransportFactory(new TBufferedTransportFactory());
     transportFactory = bufferedTransportFactory;
   }
 
@@ -628,14 +632,13 @@
   cout << endl;
 
   // Server
+  boost::shared_ptr<apache::thrift::server::TServer> server;
+
   if (server_type == "simple") {
-    TSimpleServer simpleServer(testProcessor,
+    server.reset(new TSimpleServer(testProcessor,
                                serverSocket,
                                transportFactory,
-                               protocolFactory);
-
-    simpleServer.serve();
-
+                               protocolFactory));
   } else if (server_type == "thread-pool") {
 
     boost::shared_ptr<ThreadManager> threadManager =
@@ -648,37 +651,49 @@
 
     threadManager->start();
 
-    TThreadPoolServer threadPoolServer(testProcessor,
+    server.reset(new TThreadPoolServer(testProcessor,
                                        serverSocket,
                                        transportFactory,
                                        protocolFactory,
-                                       threadManager);
-
-    threadPoolServer.serve();
-
+                                       threadManager));
   } else if (server_type == "threaded") {
 
-    TThreadedServer threadedServer(testProcessor,
+    server.reset(new TThreadedServer(testProcessor,
                                    serverSocket,
                                    transportFactory,
-                                   protocolFactory);
-
-    threadedServer.serve();
-
+                                   protocolFactory));
   } else if (server_type == "nonblocking") {
     if(transport_type == "http") {
       boost::shared_ptr<TestHandlerAsync> testHandlerAsync(new TestHandlerAsync(testHandler));
       boost::shared_ptr<TAsyncProcessor> testProcessorAsync(new ThriftTestAsyncProcessor(testHandlerAsync));
       boost::shared_ptr<TAsyncBufferProcessor> testBufferProcessor(new TAsyncProtocolProcessor(testProcessorAsync, protocolFactory));
-      
+
+      // not loading nonblockingServer into "server" because
+      // TEvhttpServer doesn't inherit from TServer, and doesn't
+      // provide a stop method.
       TEvhttpServer nonblockingServer(testBufferProcessor, port);
       nonblockingServer.serve();
-} else {
-      TNonblockingServer nonblockingServer(testProcessor, port);
-      nonblockingServer.serve();
+    } else {
+      server.reset(new TNonblockingServer(testProcessor, port));
     }
   }
 
+  if(server.get() != NULL)
+  {
+    apache::thrift::concurrency::PlatformThreadFactory factory;
+    factory.setDetached(false);
+    boost::shared_ptr<apache::thrift::concurrency::Runnable> serverThreadRunner(server);
+    boost::shared_ptr<apache::thrift::concurrency::Thread> thread = factory.newThread(serverThreadRunner);
+    thread->start();
+
+    cout<<"Press enter to stop the server."<<endl;
+    cin.ignore(); //wait until a key is pressed
+
+    server->stop();
+    thread->join();
+    server.reset();
+  }
+
   cout << "done." << endl;
   return 0;
 }
diff --git a/test/threads/ThreadsClient.cpp b/test/threads/ThreadsClient.cpp
index 70b08ad..9306a3f 100644
--- a/test/threads/ThreadsClient.cpp
+++ b/test/threads/ThreadsClient.cpp
@@ -28,6 +28,9 @@
 #include <thrift/concurrency/Monitor.h>
 #include <thrift/concurrency/ThreadManager.h>
 #include <thrift/concurrency/PlatformThreadFactory.h>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 using boost::shared_ptr;
 using namespace apache::thrift;
@@ -37,6 +40,9 @@
 using namespace apache::thrift::concurrency;
 
 int main(int argc, char **argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
   int port = 9090;
   std::string host = "localhost";
 
diff --git a/test/threads/ThreadsServer.cpp b/test/threads/ThreadsServer.cpp
index 9c1a7d9..a267c3b 100644
--- a/test/threads/ThreadsServer.cpp
+++ b/test/threads/ThreadsServer.cpp
@@ -29,6 +29,9 @@
 #include <thrift/concurrency/Monitor.h>
 #include <thrift/concurrency/ThreadManager.h>
 #include <thrift/concurrency/PlatformThreadFactory.h>
+#if _WIN32
+   #include <thrift/windows/TWinsockSingleton.h>
+#endif
 
 using boost::shared_ptr;
 using namespace apache::thrift;
@@ -85,11 +88,12 @@
 protected:
   void go2sleep(int thread, int seconds) {
     Monitor m;
+    Synchronized s(m);
     for (int i = 0; i < seconds; ++i) {
       fprintf(stderr, "Thread %d: sleep %d\n", thread, i);
       try {
         m.wait(1000);
-      } catch(TimedOutException& e) {
+      } catch(const TimedOutException&) {
       }
     }
     fprintf(stderr, "THREAD %d DONE\n", thread);
@@ -101,6 +105,9 @@
 };
 
 int main(int argc, char **argv) {
+#if _WIN32
+  transport::TWinsockSingleton::create();
+#endif
   int port = 9090;
   shared_ptr<ThreadsTestHandler> handler(new ThreadsTestHandler());
   shared_ptr<TProcessor> processor(new ThreadsTestProcessor(handler));