winix/core/threadmanager.cpp

105 lines
1.7 KiB
C++
Executable File

/*
* This file is a part of Winix
* and is not publicly distributed
*
* Copyright (c) 2011, Tomasz Sowa
* All rights reserved.
*
*/
#include <signal.h>
#include "threadmanager.h"
#include "log.h"
ThreadManager::ThreadManager()
{
were_started = false;
}
void ThreadManager::SetSynchro(Synchro * psynchro)
{
synchro = psynchro;
}
void ThreadManager::Init()
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGINT);
// blocking SIGTERM and SIGINT
// new threads will have the signals blocked too
pthread_sigmask(SIG_BLOCK, &set, 0);
}
void ThreadManager::Add(BaseThread * pbase)
{
thread_tab.push_back(pbase);
if( were_started )
Start(thread_tab.size() - 1);
else
log << log4 << "TM: added a thread to the queue, number: " << (thread_tab.size()-1) << logend;
}
void ThreadManager::StartAll()
{
for(size_t i=0 ; i<thread_tab.size() ; ++i)
Start(i);
were_started = true;
}
void ThreadManager::Start(size_t i)
{
if( i < thread_tab.size() )
{
if( thread_tab[i]->StartThread() )
{
log << log4 << "TM: thread " << i << " (" << thread_tab[i]->ThreadId() << ") started" << logend;
}
else
{
log << log4 << "TM: cannot run a thread, thread number: " << i << logend;
}
}
}
void ThreadManager::StopAll()
{
if( !were_started )
return;
// WakeUpThread() should be used with Lock/Unlock
synchro->Lock();
for(size_t i=0 ; i<thread_tab.size() ; ++i)
thread_tab[i]->WakeUpThread();
synchro->Unlock();
for(size_t i=0 ; i<thread_tab.size() ; ++i)
{
log << log4 << "TM: waiting for thread " << i << " (" << thread_tab[i]->ThreadId() << ")" << logend;
thread_tab[i]->WaitForThread();
log << log4 << "TM: thread " << i << " terminated" << logend;
}
}