I have written a simple singleton application.
The following is my sample main class
// ThreadsafeSingletonUsingSemaphore.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include "MySingleton.h"
using namespace std;
int i =0;
#define THREADCOUNT 100
DWORD WINAPI ThreadProc(LPVOID lParam);
HANDLE g_semaphore = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
g_semaphore = CreateSemaphore(NULL,1,1,_T("TreadOne"));
HANDLE hThread[THREADCOUNT];
DWORD aThreadID;
for(int iCount = 0; iCount < THREADCOUNT ; iCount++)
{
hThread[iCount] = CreateThread(NULL, 0, ThreadProc, 0,0, &aThreadID);
if( hThread[iCount] == NULL )
{
cout<<"CreateThread error: %d" << GetLastError() << endl;
return 1;
}
}
WaitForMultipleObjects(THREADCOUNT, hThread, TRUE, INFINITE);
// Close thread and semaphore handles
for(int i=0; i < THREADCOUNT; i++ )
CloseHandle(hThread[i]);
cout << MySingleton::getInstance().getCounter() << endl ;
CloseHandle(g_semaphore);
_getch();
return 0;
}
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
//DWORD result = WaitForSingleObject(g_semaphore,INFINITE);
//if(WAIT_OBJECT_0 == result)
MySingleton::getInstance().incrementCouner();
//ReleaseSemaphore(g_semaphore,1, NULL);
return TRUE;
}
This is my singleton implementation class.
#include "StdAfx.h"
#include "MySingleton.h"
MySingleton* MySingleton::m_instance = NULL;
HANDLE MySingleton::m_hSem = CreateSemaphore(NULL, 1, 1, _T("MySingleton"));
HANDLE MySingleton::m_One = CreateSemaphore(NULL, 1, 1, _T("MyOne"));
MySingleton::MySingleton(void) : m_counter(0)
{
}
MySingleton::~MySingleton(void)
{
cout << "destructor" << endl;
CloseHandle(m_hSem);
CloseHandle(m_One);
}
MySingleton& MySingleton::getInstance()
{
DWORD result = WaitForSingleObject(m_hSem, INFINITE);
if(WAIT_OBJECT_0 == result)
{
if(m_instance == NULL)
{
cout << "creating" << endl;
m_instance = new MySingleton();
}
}
ReleaseSemaphore(m_hSem,1,NULL);
return *m_instance;
}
void MySingleton::setCouner(int iCount_in)
{
m_counter = iCount_in;
}
int MySingleton::getCounter()
{
return m_counter;
}
void MySingleton::incrementCouner()
{
DWORD result = WaitForSingleObject(m_One, INFINITE);
if(WAIT_OBJECT_0 == result)
m_counter++;
ReleaseSemaphore(m_One,1,NULL);
}
This is my .h class.
#pragma once
#include <windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
class MySingleton
{
private:
static HANDLE m_hSem, m_One;
HANDLE m_hCountSem;
static MySingleton* m_instance;
int m_counter;
MySingleton();
MySingleton(const MySingleton& obj_in);
MySingleton& operator=(const MySingleton& obj_in);
public:
~MySingleton(void);
static MySingleton& getInstance();
void setCouner(int iCount_in);
int getCounter();
void incrementCouner();
};
The problem is the final value of counter is never 100. can someone please explain me why and what is that i am doing wrong.I am not able to understand the problem. When I introduce sleep in the main before creating each thread, it works fine.
The problem is that call to WaitForMultipleObjects handles up to MAXIMUM_WAIT_OBJECTS which, at least in Visual Studio 2017, is 64.
Notice how your call to WaitForMultipleObjects to join threads returns WAIT_FAILED.
In order to wait for more objects one should, according to the documentation:
To wait on more than MAXIMUM_WAIT_OBJECTS handles, use one of the following methods:
Create a thread to wait on MAXIMUM_WAIT_OBJECTS handles, then wait on that thread plus the other handles. Use this technique to break the handles into groups of MAXIMUM_WAIT_OBJECTS.
Call RegisterWaitForSingleObject to wait on each handle. A wait thread from the thread pool waits on MAXIMUM_WAIT_OBJECTS registered objects and assigns a worker thread after the object is signaled or the time-out interval expires.
You don't need to write all of that code. The easiest way to implement a threadsafe singleton is to use Scott Meyer's singleton idiom:
class Singleton {
int counter;
mutable std::mutex counter_guard;
Singleton() {}
public:
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
static Singleton& instance() {
static Singleton theInstance;
return theInstance;
}
void setCounter(int newVal) {
std::unique_lock<std::mutex> lock(counter_guard);
counter = newVal;
}
void incrementCounter() {
std::unique_lock<std::mutex> lock(counter_guard);
++counter;
}
int getCounter() const {
std::unique_lock<std::mutex> lock(counter_guard);
return counter;
}
};
An even easier way would be to use a std::atomic<int> type for the counter member variable. Then the mutex and lock guards can be omitted at all.
Related
I'm using std::thread to launch threads. Also, I need stats for the worker thread available at /proc/[pid]/tasks/[tid]. I need tid to be able to monitor thread stats. I was wondering if there was a way to extract tid from the parent thread. I know that syscall gettid() from the worker returns its id, but I want the threadId from the master and not the slave. Is there a way to extract tid from the thread_id gor from std::thread.get_tid() ?
I believe there might be better ways of doing this, please suggest :)
UPDATE:
How can you get the Linux thread Id of a std::thread() this provides some information on getting tid from the worker, adds an overhead to the thread launch. For instance, std::thread t = std::thread(&wrapper); t.get_id() can be called from the launcher thread. I was/am looking if there was a to do the same thing from the main/launcher thread in a safe way.
All threads have a unique id:
std::thread::id this_id = std::this_thread::get_id();
You can store it in a variable when the program starts and it'll be accessible from the other threads.
I understand what you mean when you say parent thread, but even though one thread gave birth to another, they are siblings.
if you want the master thread to be able to get the /proc path to each worker thread, you could wrap the worker thread object in a class that, when it starts the actual thread, creates a path property that the master can later get.
An example:
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
// A base class for thread object wrappers
class abstract_thread {
public:
abstract_thread() {}
abstract_thread(const abstract_thread&) = delete;
abstract_thread(abstract_thread&& rhs) :
m_th(std::move(rhs.m_th)), m_terminated(rhs.m_terminated), m_cv{}, m_mtx{} {}
abstract_thread& operator=(const abstract_thread&) = delete;
abstract_thread& operator=(abstract_thread&& rhs) {
terminate();
join();
m_th = std::move(rhs.m_th);
m_terminated = rhs.m_terminated;
return *this;
}
virtual ~abstract_thread() {
// make sure we don't destroy a running thread object
terminate();
join();
}
virtual void start() {
if(joinable())
throw std::runtime_error("thread already running");
else {
std::unique_lock<std::mutex> lock(m_mtx);
m_terminated = true;
// start thread and wait for it to signal that setup has been done
m_th = std::thread(&abstract_thread::proxy, this);
m_cv.wait(lock, [this] { return m_terminated == false; });
}
}
inline bool joinable() const { return m_th.joinable(); }
inline void join() {
if(joinable()) {
m_th.join();
}
}
inline void terminate() { m_terminated = true; }
inline bool terminated() const { return m_terminated; }
protected:
// override if thread specific setup needs to be done before start() returns
virtual void setup_in_thread() {}
// must be overridden in derived classes
virtual void execute() = 0;
private:
std::thread m_th{};
bool m_terminated{};
std::condition_variable m_cv{};
std::mutex m_mtx{};
void proxy() {
{
std::unique_lock<std::mutex> lock(m_mtx);
setup_in_thread(); // call setup function
m_terminated = false;
m_cv.notify_one();
}
execute(); // run thread code
}
};
// an abstract thread wrapper capable of returning its /proc path
class proc_path_thread : public abstract_thread {
public:
// function to call from master to get the path
const std::string& get_proc_path() const { return m_proc_path; }
protected:
void setup_in_thread() override {
m_proc_path =
std::move(std::string("/proc/")) + std::to_string(syscall(SYS_gettid));
}
private:
std::string m_proc_path{};
};
// two different thread wrapper classes. Just inherit proc_path_thread and implement
// "execute()". Loop until terminated() is true (or you're done with the work)
class AutoStartThread : public proc_path_thread {
public:
AutoStartThread() { start(); }
private:
void execute() override {
while(!terminated()) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << std::this_thread::get_id() << " AutoStartThread running\n";
}
}
};
class ManualStartThread : public proc_path_thread {
void execute() override {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << std::this_thread::get_id() << " ManualStartThread running\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
int main() {
AutoStartThread a;
std::cout << a.get_proc_path() << "\t// AutoStartThread, will have path\n";
ManualStartThread b;
std::cout << b.get_proc_path()
<< "\t// ManualStartThread not started, no path\n";
b.start();
std::cout << b.get_proc_path()
<< "\t// ManualStartThread will now have a path\n";
b.join();
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
// terminate() + join() is called automatically when abstract_thread descendants
// goes out of scope:
//
// a.terminate();
// a.join();
}
Possible output:
/proc/38207 // AutoStartThread, will have path
// ManualStartThread not started, no path
/proc/38208 // ManualStartThread will now have a path
139642064209664 ManualStartThread running
139642072602368 AutoStartThread running
139642072602368 AutoStartThread running
139642072602368 AutoStartThread running
139642072602368 AutoStartThread running
You can launch the thread through a function whose first task will be to message it's id, e.g., either classically using mutexes and condvars:
#include <stdio.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
struct tid_msg{
pthread_mutex_t mx;
pthread_cond_t cond;
pid_t tid;
};
void *thr(void*A)
{
struct tid_msg *msg = A;
pid_t tid = syscall(SYS_gettid);
pthread_mutex_lock(&msg->mx);
msg->tid = tid;
pthread_mutex_unlock(&msg->mx);
pthread_cond_signal(&msg->cond);
printf("my tid=%lu\n", (long unsigned)tid);
return 0;
}
int main()
{
struct tid_msg msg = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, -1 };
pthread_t ptid;
pthread_create(&ptid,0,thr,&msg);
pthread_mutex_lock(&msg.mx);
while(-1==msg.tid) pthread_cond_wait(&msg.cond,&msg.mx);
pthread_mutex_unlock(&msg.mx);
printf("their tid=%lu\n", (long unsigned)msg.tid);
pthread_join(ptid,0);
}
or simply via an atomic variable (relaxed memory ordering should be fine here,
but you can play it safe and use the sequentially consistent default):
#include <stdio.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <stdatomic.h>
void *thr(void*A)
{
_Atomic pid_t *tidp = A;
pid_t tid;
tid = syscall(SYS_gettid);
atomic_store_explicit(tidp, tid, memory_order_relaxed);
printf("my tid=%lu\n", (long unsigned)tid);
return 0;
}
int main()
{
_Atomic pid_t tid=-1;
pthread_t ptid;
pthread_create(&ptid,0,thr,&tid);
while(-1==atomic_load_explicit(&tid,memory_order_relaxed)) ;
printf("their tid=%lu\n", (long unsigned)tid);
pthread_join(ptid,0);
}
I used the following code to create a timer object in my c++ application running on a debian 8.
class Timer
{
private:
std::condition_variable cond_;
std::mutex mutex_;
int duration;
void *params;
public:
Timer::Timer(void (*func)(void*))
{
this->handler = func;
this->duration = 0;
this->params = NULL;
};
Timer::~Timer(){};
void Timer::start(int duree, void* handlerParams)
{
this->duration = duree;
this->params = handlerParams;
/*
* Launch the timer thread and wait it
*/
std::thread([this]{
std::unique_lock<std::mutex> mlock(mutex_);
std::cv_status ret = cond_.wait_for(mlock,
std::chrono::seconds(duration));
if ( ret == std::cv_status::timeout )
{
handler(params);
}
}).detach();
};
void Timer::stop()
{
cond_.notify_all();
}
};
It works correctly under gdb and under normal conditions, but in a load test of 30 requests or more, it crashes with the assertion :
nptl/pthread_mutex_lock.c:350: __pthread_mutex_cond_lock_full: Assertion `(-(e)) != 3 || !robust' failed.
I don't understand the cause of this assertion. Can anyone help me please ??
Thank you
Basically you have a detached thread that accesses the timer object, so it's likely that you destroyed the Timer object but the thread is still running and accessing it's member(mutex, conditional variable).
The assert itself says, from glibc source code, that the owner of the mutex has died.
Thanks a lot for your comments ! I'll try to change the thread detach, and do the load tests.
This is a MVCE of my problem, which is a part of a huge application.
/**
* \file Timer.hxx
* \brief Definition of Timer class.
*/
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
class Timer
{
private:
std::condition_variable cond_;
std::mutex mutex_;
int duration;
void *params;
public:
Timer(void (*func)(void*));
~Timer();
void (*handler)(void*);
void start(int duree, void* handlerParams);
void stop();
};
/*
* Timer.cxx
*/
#include "Timer.hxx"
Timer::Timer(void (*func)(void*))
{
//this->set_handler(func, params);
this->handler = func;
this->duration = 0;
this->params = NULL;
}
Timer::~Timer()
{
}
void Timer::start(int duree, void* handlerParams)
{
this->duration = duree;
this->params = handlerParams;
/*
* Launch the timer thread and wait it
*/
std::thread([this]{
std::unique_lock<std::mutex> mlock(mutex_);
std::cv_status ret = cond_.wait_for(mlock, std::chrono::seconds(duration));
if ( ret == std::cv_status::timeout )
{
handler(params);
}
}).detach();
}
void Timer::stop()
{
cond_.notify_all();
}
/*
* MAIN
*/
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include "Timer.hxx"
using namespace std;
void timeoutHandler(void* params)
{
char* data= (char*)params;
cout << "Timeout triggered !! Received data is: " ;
if (data!=NULL)
cout << data << endl;
}
int main(int argc, char **argv)
{
int delay=5;
char data[20] ="This is a test" ;
Timer *t= new Timer(&timeoutHandler) ;
t->start(delay, data);
cout << "Timer started !! " << endl;
sleep(1000);
t->stop();
delete t;
cout << "Timer deleted !! " << endl;
return 0;
}
I have experience with threads in Java but want to learn how to use them in C++11. I tried to make a simple threadpool, where threads are created once and can be asked to execute tasks.
#include <thread>
#include <iostream>
#define NUM_THREADS 2
class Worker
{
public:
Worker(): m_running(false), m_hasData(false)
{
};
~Worker() {};
void execute()
{
m_running = true;
while(m_running)
{
if(m_hasData)
{
m_system();
}
m_hasData = false;
}
};
void stop()
{
m_running = false;
};
void setSystem(const std::function<void()>& system)
{
m_system = system;
m_hasData = true;
};
bool isIdle() const
{
return !m_hasData;
};
private:
bool m_running;
std::function<void()> m_system;
bool m_hasData;
};
class ThreadPool
{
public:
ThreadPool()
{
for(int i = 0; i < NUM_THREADS; ++i)
{
m_threads[i] = std::thread(&Worker::execute, &m_workers[i]);
}
};
~ThreadPool()
{
for(int i = 0; i < NUM_THREADS; ++i)
{
std::cout << "Stopping " << i << std::endl;
m_workers[i].stop();
m_threads[i].join();
}
};
void execute(const std::function<void()>& system)
{
// Finds the first non-idle worker - not really great but just for testing
for(int i = 0; i < NUM_THREADS; ++i)
{
if(m_workers[i].isIdle())
{
m_workers[i].setSystem(system);
return;
}
}
};
private:
Worker m_workers[NUM_THREADS];
std::thread m_threads[NUM_THREADS];
};
void print(void* in, void* out)
{
char** in_c = (char**)in;
printf("%s\n", *in_c);
}
int main(int argc, const char * argv[]) {
ThreadPool pool;
const char* test_c = "hello_world";
pool.execute([&]() { print(&test_c, nullptr); });
}
The output of this is:
hello_world
Stopping 0
After that, the main thread halts, because it's waiting for the first thread to join (in the destructor of the ThreadPool). For some reason, the m_running variable of the workers is not set to false, which keeps the application running indefinitely.
In Worker::stop the member m_running is written in the main thread, while it is read in execute in a different thread. This is undefined behavior. You need to protect read/write access from different threads. In this case I would recommend using std::atomic<bool> for m_running.
Edit: the same holds for m_hasData.
i searched for an answer but couldnt find it. im working on threads. i have a thread class and 3 subclass of it. when i call one of these 3 subclass i have to create a thread in thread class and use their main(since threads main is pure virtual abstract) but the problem is before it call the Create Thread function(c'tor of thread) it calls those sub-mains.
thread.h
#ifndef _THREAD_H_
#define _THREAD_H_
#include <string>
#include <Windows.h>
#include <iosfwd>
#include "Mutex.h"
#include "SynchronizedArray.h"
#include "SynchronizedCounter.h"
std::string message = "";
class Thread{
private:
HANDLE hThread;
int idThread;
protected:
SynchronizedArray *arr;
int size;
SynchronizedCounter *counter;
public:
Thread(DWORD funct){ //creates a thread by calling subclasses main functions appropriately
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) funct, NULL, 0, (LPDWORD)&idThread);
}
virtual DWORD WINAPI main(void*) = 0; // pure virtual abstract class
void suspend(){ //suspent the thread
SuspendThread(hThread);
}
void resume(){// retume the thread
ResumeThread(hThread);
}
void terminate(){ // terminates the thread
TerminateThread(hThread,0);
}
void join(){ // joins the thread
Mutex mut;
mut.lock();
}
static void sleep(int sec){ //wrapper of sleep by sec
Sleep(sec*1000);
}
};
#endif
1 of 3 inherited class of Thread as example (all of them do the same)
PrintThread.h
#ifndef _PRINTINGTHREAD_H_
#define _PRINTINGTHREAD_H_
#include "SynchronizedArray.h"
#include "SynchronizedCounter.h"
#include "Thread.h"
#include <iostream>
#include "SortingThread.h"
#include "CountingThread.h"
#include <string>
#include <Windows.h>
extern CountingThread counterThread1;
extern CountingThread counterThread2;
extern SortingThread sortingThread1;
extern SortingThread sortingThread2;
class PrintingThread:public Thread{
private:
char temp;
public:
PrintingThread() :Thread(main(&temp)){
}
DWORD WINAPI main(void* param)
{
std::cout << "Please enter an operation ('showcounter1','showcounter2','showarray1','showarray2' or 'quit')" << std::endl;
std::cin >> message;
while (message != "quit")
{
if (message == "showcounter1")
{
std::cout << counterThread1<<std::endl;
}
else if (message == "showcounter2")
{
std::cout << counterThread2 << std::endl;
}
else if (message == "showarray1")
{
std::cout << sortingThread1 << std::endl;
}
else if (message == "showarray2")
{
std::cout << sortingThread2 << std::endl;
}
else {
std::cout << "Invalid operation";
}
std::cout << "Please enter an operation ('show counter 1','show counter 2','show array 1','show array 2' or 'quit')" << std::endl;
std::cin >> message;
}
return 0;
}
};
#endif
Why its calling mains before it calls the c'tor of thread.
Your PrintingThread constructor initializer list is actually calling PrintingThread::main and passing the result of that to the Thread constructor. That means that the CreateThread call is receiving a DWORD (in this case, 0) as its function argument.
You need to change your class design to actually pass the function pointer and context argument around, e.g.:
Thread(DWORD funct){
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) funct, NULL, 0, (LPDWORD)&idThread);
should be:
Thread(LPTHREAD_START_ROUTINE funct, LPVOID arg) {
hThread = CreateThread(NULL, 0, funct, arg, 0, (LPDWORD)&idThread);
(The fact that you had to cast funct should have been a giant red flag.)
Likewise, the subclass constructors will change from:
PrintingThread() :Thread(main(&temp)){
to:
PrintingThread(): Thread(main, &temp) {
Note that your code will still have other issues, like the fact that the thread functions should be static (so you can't try to access member functions).
you need to do something more like this instead:
thread.h:
#ifndef _THREAD_H_
#define _THREAD_H_
#include <string>
#include <Windows.h>
#include <iosfwd>
#include "Mutex.h"
#include "SynchronizedArray.h"
#include "SynchronizedCounter.h"
class Thread
{
private:
HANDLE hThread;
DWORD idThread;
void *pParam;
static DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
Thread *pThis = (Thread*) lpParameter;
return pThis->main(pThis->pParam);
}
protected:
SynchronizedArray *arr;
int size;
SynchronizedCounter *counter;
public:
Thread(void *aParam)
{
//creates a thread by calling subclasses main functions appropriately
pParam = aParam;
hThread = CreateThread(NULL, 0, &ThreadProc, this, 0, &idThread);
}
virtual DWORD main(void*) = 0; // pure virtual abstract class
void suspend()
{
//suspent the thread
SuspendThread(hThread);
}
void resume()
{
// resume the thread
ResumeThread(hThread);
}
void terminate()
{
// terminates the thread
TerminateThread(hThread, 0);
}
void join()
{
// joins the thread
Mutex mut;
mut.lock();
}
static void sleep(int sec)
{
//wrapper of sleep by sec
Sleep(sec*1000);
}
};
#endif
PrintThread.h:
include <iostream>
#include "SortingThread.h"
#include "CountingThread.h"
#include <string>
#include <Windows.h>
extern CountingThread counterThread1;
extern CountingThread counterThread2;
extern SortingThread sortingThread1;
extern SortingThread sortingThread2;
class PrintingThread : public Thread
{
private:
char temp;
public:
PrintingThread() : Thread(&temp)
{
}
virtual DWORD main(void* param)
{
std::string message;
do
{
std::cout << "Please enter an operation ('showcounter1','showcounter2','showarray1','showarray2' or 'quit')" << std::endl;
std::cin >> message;
if (message == "quit")
{
break;
}
if (message == "showcounter1")
{
std::cout << counterThread1 << std::endl;
}
else if (message == "showcounter2")
{
std::cout << counterThread2 << std::endl;
}
else if (message == "showarray1")
{
std::cout << sortingThread1 << std::endl;
}
else if (message == "showarray2")
{
std::cout << sortingThread2 << std::endl;
}
else
{
std::cout << "Invalid operation";
}
}
while (true);
return 0;
}
};
#endif
I have a class defined like this: This is not all complete and probably won't compile.
class Server
{
public:
Server();
~Server();
class Worker
{
public:
Worker(Server& server) : _server(server) { }
~Worker() { }
void Run() { }
void Stop() { }
private:
Server& _server;
}
void Run()
{
while(true) {
// do work
}
}
void Stop()
{
// How do I stop the thread?
}
private:
std::vector<Worker> _workers;
};
My question is, how do I initialize the workers array passing in the outer class named Server.
What I want is a vector of worker threads. Each worker thread has it's own state but can access some other shared data (not shown). Also, how do I create the threads. Should they be created when the class object is first created or externally from a thread_group.
Also, how do I go about shutting down the threads cleanly and safely?
EDIT:
It seems that I can initialize Worker like this:
Server::Server(int thread_count)
: _workers(thread_count), Worker(*this)), _thread_count(thread_count) { }
And I'm currently doing this in Server::Run to create the threads.
boost::thread_group _threads; // a Server member variable
Server::Run(){
for (int i = 0; i < _thread_count; i++)
_threads.create_thread(boost::bind(&Server::Worker::Run, _workers(i)));
// main thread.
while(1) {
// Do stuff
}
_threads.join_all();
}
Does anyone see any problems with this?
And how about safe shutdown?
EDIT:
One problem I have found with it is that the Worker objects don't seem to get constructed!
oops. Yes they do I need a copy constructor on the Worker class.
But oddly, creating the threads results in the copy constructor for Worker being called multiple times.
I have done it with pure WINAPI, look:
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
class Server
{
public:
class Worker
{
int m_id;
DWORD m_threadId;
HANDLE m_threadHandle;
bool m_active;
friend Server;
public:
Worker (int id)
{
m_id = id;
m_threadId = 0;
m_threadHandle = 0;
m_active = true;
}
static DWORD WINAPI Run (LPVOID lpParam)
{
Worker* p = (Worker*) lpParam; // it's needed because of the static modifier
while (p->m_active)
{
printf ("I'm a thread #%i\n", p->m_id);
Sleep (1000);
}
return 0;
}
void Stop ()
{
m_active = false;
}
};
Server ()
{
m_workers = new vector <Worker*> ();
m_count = 0;
}
~Server ()
{
delete m_workers;
}
void Run ()
{
puts ("Server is run");
}
void Stop ()
{
while (m_count > 0)
RemoveWorker ();
puts ("Server has been stopped");
}
void AddWorker ()
{
HANDLE h;
DWORD threadId;
Worker* n = new Worker (m_count ++);
m_workers->push_back (n);
h = CreateThread (NULL, 0, Worker::Run, (VOID*) n, CREATE_SUSPENDED, &threadId);
n->m_threadHandle = h;
n->m_threadId = threadId;
ResumeThread (h);
}
void RemoveWorker ()
{
HANDLE h;
DWORD threadId;
if (m_count <= 0)
return;
Worker* n = m_workers->at (m_count - 1);
m_workers->pop_back ();
n->Stop ();
TerminateThread (n->m_threadHandle, 0);
m_count --;
delete n;
}
private:
int m_count;
vector <Worker*>* m_workers;
};
int main (void)
{
Server a;
int com = 1;
a.Run ();
while (com)
{
if (kbhit ())
{
switch (getch ())
{
case 27: // escape key code
com = 0;
break;
case 'a': // add worker
a.AddWorker ();
break;
case 'r': // remove worker
a.RemoveWorker ();
break;
}
}
}
a.Stop ();
return 0;
}
There are no synchronization code here, because I haven't enougth time to do it... But I wish it will help you =)
Have you looked at boost asio at all? It looks like it could be a good fit for what you are trying to do. Additionally you can call boost asio's io_service's run (similar to your Run method) from many threads i.e. you can process your IO in many threads. Also of interest could be http://think-async.com/Asio/Recipes for an asio based thread-pool.
Have a look at the asio examples. Perhaps they offer an alternative way of handling what you are trying to do. Esp. have a look at how a clean shutdown is accomplished.