Exemplo n.º 1
0
void SuiteStartStop::Test()
{
    Thread* threadA = new TestThread("THDA", 'A');
    Thread* threadB = new TestThread("THDB", 'B');

    TEST( ((Thread&) *threadA) == ((Thread&) *threadA) );
    TEST( ((Thread&) *threadA) != ((Thread&) *threadB) );

    threadA->Start();
    threadB->Start();

    for( TUint i = 0 ; i< 10; ++i) {
        TEST(gTestStack->IsEmpty());
        threadA->Signal();
        // use sleeps to avoid dependency on thread priorities being supported
        Thread::Sleep(kSleepMs);
        TEST(gTestStack->Pop('A'));

        threadB->Signal();
        Thread::Sleep(kSleepMs);
        TEST(gTestStack->Pop('B'));

        threadA->Signal();
        Thread::Sleep(kSleepMs);
        TEST(gTestStack->Pop('A'));
    }
    TEST(gTestStack->IsEmpty());

    delete threadA;
    delete threadB;
}
Exemplo n.º 2
0
void test_rwlock(Ardb& db)
{
    WriteTask wtask;
    ReadTask rtask;
    std::map<int, int> mm;
    SpinRWLock lock;
    wtask.lock = &lock;
    wtask.mm = &mm;
    rtask.lock = &lock;
    rtask.mm = &mm;
    Thread* w = new Thread(&wtask);
    std::vector<Thread*> ts;
    for(uint32 i = 0; i < 10; i++)
    {
        Thread* r = new Thread(&rtask);
        r->Start();
        ts.push_back(r);
    }
    w->Start();
    w->Join();
    std::vector<Thread*>::iterator tit = ts.begin();
    while(tit != ts.end())
    {
        (*tit)->Join();
        tit++;
    }
    INFO_LOG("mm size=%u", mm.size());
}
Exemplo n.º 3
0
void SuitePriority::Test()
{
    Thread* threadA = new TestThread("THDA", 'A', kPriorityLow);
    Thread* threadB = new TestThread("THDB", 'B', kPriorityLow + kPriorityLess);
    TEST(gTestStack->IsEmpty());

    threadA->Start();
    threadB->Start();
    TEST(gTestStack->IsEmpty());
    threadA->Signal();
    threadB->Signal();
    TEST(gTestStack->IsEmpty());
    Thread::Sleep(kSleepMs);
    TEST(gTestStack->Pop('B')); //thread B ran second
    TEST(gTestStack->Pop('A')); //thread A ran first
    TEST(gTestStack->IsEmpty());
    delete threadA;
    delete threadB;

    threadA = new TestThread("THDA", 'a', kPriorityLowest);
    threadB = new TestThread("THDB", 'b', kPriorityLowest+1);
    TEST(gTestStack->IsEmpty());

    threadA->Start();
    threadB->Start();
    threadA->Signal();
    threadB->Signal();
    Thread::Sleep(kSleepMs);
    TEST(gTestStack->Pop('a')); //thread A ran second
    TEST(gTestStack->Pop('b')); //thread B ran first
    TEST(gTestStack->IsEmpty());
    delete threadA;
    delete threadB;
}
Exemplo n.º 4
0
int ThreadPool::CreateThreadPool()
{

    for(int i = 0; i<getMaxThreadsNumber(); i++)
    {
        int rc = 0;
        //init lock
        Thread* th = static_cast< Thread* >(new CommonSocketThread());
        /// used to
        th->setInitLocker(	&m_initThread	);
        th->setLocker(	&m_worksLock	);
        th->setThreadId(i);

        m_initThread.lock();
        rc = th->Start();
        th->getCondition().wait(&m_initThread);
        m_initThread.unlock();

        assert(rc == 0);
        m_threadMap.insert( make_pair(i, th) );



    }

    return 0;
}
Exemplo n.º 5
0
void TestThread()
{
    Thread* th = new MainTestThread();
    th->Start();
    th->Wait();
    delete th;
}
Exemplo n.º 6
0
bool ThreadPoolImpl::Execute(Runnable *pRunnable)
{
	if (0 == pRunnable || !m_bCreate) {
		return false;
	}

	bool bRet = false;
	if (m_tasks.size() >= m_nMaxPendingTask)
	{
		if (m_threads.size() < m_nMaxThread) {
			Thread *pThread = new Thread(new ThreadPoolImpl::Worker(this, pRunnable));
			if (0 != pThread) {
				TAutoLock lock(m_mtxThread);
				m_threads.push_back(pThread);
				pThread->Start();
				bRet = true;
			}
		}
		else {
			// abandon the task.
			bRet = false;
		}
	}
	else
	{
		TAutoLock lock(m_mtxTasks);
		m_tasks.push_back(pRunnable);
		bRet = true;
	}

	return bRet;
}
Exemplo n.º 7
0
void TestTimer(Environment& aEnv)
{
    Thread* th = new TimerTestThread(aEnv);
    th->Start();
    th->Wait();
    delete th;
}
Exemplo n.º 8
0
void Window2_Created(Win32Window* window)
{
	glwindow = window;

	worker.Attach(&THREAD_Run);
	worker.Start();
}
Exemplo n.º 9
0
void TestNetwork(const std::vector<Brn>& aArgs)
{
    OptionParser parser;
    OptionUint adapter("-i", "--interface", 0, "index of network adapter to use");
    parser.AddOption(&adapter);
    if (!parser.Parse(aArgs) || parser.HelpDisplayed()) {
        return;
    }

    std::vector<NetworkAdapter*>* ifs = Os::NetworkListAdapters(Net::InitialisationParams::ELoopbackUse, "TestNetwork");
    ASSERT(ifs->size() > 0 && adapter.Value() < ifs->size());
    TIpAddress addr = (*ifs)[adapter.Value()]->Address();
    for (TUint i=0; i<ifs->size(); i++) {
        (*ifs)[i]->RemoveRef("TestNetwork");
    }
    delete ifs;
    Endpoint endpt(0, addr);
    Endpoint::AddressBuf buf;
    endpt.AppendAddress(buf);
    Print("Using network interface %s\n\n", buf.Ptr());
    Thread* th = new MainNetworkTestThread(addr);
    th->Start();
    th->Wait();
    delete th;
}
Exemplo n.º 10
0
bool ThreadPoolImpl::Create(unsigned int nMinThread, unsigned int nMaxThread, unsigned int nMaxPendingTask)
{
	if (m_bCreate) {	// disallow recreate operation.
		return true;	// discard the recreate parameters (i.e. nMin, nMax, nMax)
	}

	if (0 == nMinThread || nMinThread > nMaxThread) {
		return false;
	}

	m_nMinThread = nMinThread;
	m_nMaxThread = nMaxThread;
	m_nMaxPendingTask = nMaxPendingTask;

	unsigned int i = 0;
	for (; i < m_nMinThread; ++i)
	{
		Thread *pThread = new Thread(new ThreadPoolImpl::Worker(this, 0));
		if (0 == pThread) {
			break;
		}
		TAutoLock lock(m_mtxThread);
		m_threads.push_back(pThread);
		pThread->Start();
	}

	m_bCreate = i > 0 ? true : false;
	return m_bCreate;
}
Exemplo n.º 11
0
	int Ardb::FlushAll()
	{
		struct VisitorTask: public RawValueVisitor, public Thread
		{
				Ardb* db;
				VisitorTask(Ardb* adb) :
						db(adb)
				{
				}
				int OnRawKeyValue(const Slice& key, const Slice& value)
				{
					db->RawDel(key);
					return 0;
				}
				void Run()
				{
					db->GetEngine()->BeginBatchWrite();
					db->VisitAllDB(this);
					db->GetEngine()->CommitBatchWrite();
					db->GetEngine()->CompactRange(Slice(), Slice());
					delete this;
				}
		};
		/*
		 * Start a background thread to delete kvs
		 */
		Thread* t = new VisitorTask(this);
		t->Start();
		return 0;
	}
Exemplo n.º 12
0
	int Ardb::CompactDB(const DBID& db)
	{
		struct CompactTask: public Thread
		{
				Ardb* adb;
				DBID dbid;
				CompactTask(Ardb* db, DBID id) :
						adb(db), dbid(id)
				{
				}
				void Run()
				{
					KeyObject start(Slice(), KV, dbid);
					KeyObject end(Slice(), KV, dbid + 1);
					Buffer sbuf, ebuf;
					encode_key(sbuf, start);
					encode_key(ebuf, end);
					adb->GetEngine()->CompactRange(sbuf.AsString(), ebuf.AsString());
					delete this;
				}
		};
		/*
		 * Start a background thread to compact kvs
		 */
		Thread* t = new CompactTask(this, db);
		t->Start();
		return 0;
	}
Exemplo n.º 13
0
void SuiteThreadKill::Test()
{
    Semaphore sem("", 0);
    Thread* th = new ThreadKillable(sem);
    th->Start();
    sem.Wait();
    delete th;
}
Exemplo n.º 14
0
void TestThread()
{
    gTestStack = new TestStack();
    Thread* th = new MainTestThread();
    th->Start();
    th->Wait();
    delete th;
    delete gTestStack;
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    Thread *thread = new Thread();
    thread->SetThreadType(ThreadTypeIntervalBased, 10);

    TestTask *task = new TestTask();

    thread->AddTask(task);
    thread->Start();
}
Exemplo n.º 16
0
bool Mail(NickCore *nc, const Anope::string &subject, const Anope::string &message)
{
	if (!Config->UseMail || !nc || nc->email.empty() || subject.empty() || message.empty())
		return false;

	nc->lastmail = Anope::CurTime;
	Thread *t = new MailThread(nc->display, nc->email, subject, message);
	t->Start();

	return true;
}
Exemplo n.º 17
0
		void TcpClient::StartReceiveData(void(*ReceiveFunction) (char*, int))
		{
			__PRIVATE_TCPCLIENT::ReceiveDataParameter* parameter = new (__PRIVATE_TCPCLIENT::ReceiveDataParameter);
			parameter->ReceiveFunction = ReceiveFunction;
			parameter->ConnectionLostFunction = ConnectionLost;
			parameter->Socket = _socket,
				parameter->BufferSize = _bufferSize;

			Thread thread = Thread(__PRIVATE_TCPCLIENT::ReceiveData, parameter);
			thread.Start();
		}
Exemplo n.º 18
0
      /**
       * \brief Test the creation and join of thread. 
       */
      void testThreadCreate()
      {
        void* ret = NULL;
        Callback obj;
        Thread th = Thread(new ThreadArgImpl<Callback>(obj, &Callback::Call, NULL));

        th.Start(false);
        th.Join(&ret);

        CPPUNIT_ASSERT(ret == (void*)0xABCD);
      }
Exemplo n.º 19
0
		int StartThread() {
			WAWO_ASSERT( m_thread == NULL );
			try {
				m_thread = new Thread( this, "ThreadObject" );
			} catch(...) {
				WAWO_DELETE(m_thread);
				int _eno = wawo::GetLastErrno();
				WAWO_FATAL("[ThreadObject_Abstract::StartThread] failed: %d", _eno );
				return _eno;
			}
			return m_thread->Start();
		}
Exemplo n.º 20
0
bool Mail::Send(NickServ::Account *nc, const Anope::string &subject, const Anope::string &message)
{
	Configuration::Block *b = Config->GetBlock("mail");
	if (!b->Get<bool>("usemail") || b->Get<Anope::string>("sendfrom").empty() || !nc || nc->GetEmail().empty() || subject.empty() || message.empty())
		return false;

	nc->lastmail = Anope::CurTime;
	Thread *t = new Mail::Message(b->Get<Anope::string>("sendfrom"), nc->GetDisplay(), nc->GetEmail(), subject, message);
	t->Start();

	return true;
}
Exemplo n.º 21
0
int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        std::cout << "Insuficient parameters: host port [nick] [user]" << std::endl;
        return 1;
    }

    char* host = argv[1];
    int port = atoi(argv[2]);
    std::string nick("MyIRCClient");
    std::string user("IRCClient");

    if (argc >= 4)
        nick = argv[3];
    if (argc >= 5)
        user = argv[4];

    IRCClient client;

    client.Debug(true);

    // Start the input thread
    Thread thread;
    thread.Start(&inputThread, &client);

    if (client.InitSocket())
    {
        std::cout << "Socket initialized. Connecting..." << std::endl;

        if (client.Connect(host, port))
        {
            std::cout << "Connected. Loggin in..." << std::endl;

            if (client.Login(nick, user))
            {
                std::cout << "Logged." << std::endl;

                running = true;
                signal(SIGINT, signalHandler);

                while (client.Connected() && running)
                    client.ReceiveData();
            }

            if (client.Connected())
                client.Disconnect();

            std::cout << "Disconnected." << std::endl;
        }
    }
}
Exemplo n.º 22
0
bool Mail::Send(User *u, NickServ::Account *nc, ServiceBot *service, const Anope::string &subject, const Anope::string &message)
{
	if (!nc || !service || subject.empty() || message.empty())
		return false;

	Configuration::Block *b = Config->GetBlock("mail");

	if (!u)
	{
		if (!b->Get<bool>("usemail") || b->Get<Anope::string>("sendfrom").empty())
			return false;
		else if (nc->GetEmail().empty())
			return false;

		nc->lastmail = Anope::CurTime;
		Thread *t = new Mail::Message(b->Get<Anope::string>("sendfrom"), nc->GetDisplay(), nc->GetEmail(), subject, message);
		t->Start();
		return true;
	}
	else
	{
		if (!b->Get<bool>("usemail") || b->Get<Anope::string>("sendfrom").empty())
			u->SendMessage(service, _("Services have been configured to not send mail."));
		else if (Anope::CurTime - u->lastmail < b->Get<time_t>("delay"))
			u->SendMessage(service, _("Please wait \002%d\002 seconds and retry."), b->Get<time_t>("delay") - (Anope::CurTime - u->lastmail));
		else if (nc->GetEmail().empty())
			u->SendMessage(service, _("E-mail for \002%s\002 is invalid."), nc->GetDisplay().c_str());
		else
		{
			u->lastmail = nc->lastmail = Anope::CurTime;
			Thread *t = new Mail::Message(b->Get<Anope::string>("sendfrom"), nc->GetDisplay(), nc->GetEmail(), subject, message);
			t->Start();
			return true;
		}

		return false;
	}
}
Exemplo n.º 23
0
//----------------------------------------------------------------------------
bool ThreadServer::StartThreads (int threadsNum)
{
	if (0 == threadsNum)
		return false;

	for (int i=0; i<threadsNum; i++)
	{
		Thread *thread = new0 Thread();
		thread->Start(*this);
		mThreads.push_back(thread);
	}

	return true;
}
Exemplo n.º 24
0
	void Program::Run()
	{
		Thread* th = new Thread(new ThreadStart(DELEGATE_FUNC(Program::target1)));
		Thread* th2 = new Thread(new ThreadStart(DELEGATE_FUNC(Program::target2)));
		Console::WriteLine(new String("Start threads"));
		th->Start();
		th2->Start();
		Thread::Sleep(5000);
		Console::WriteLine(new String("Abort Target 2"));
		th2->Abort();
		Console::WriteLine(new String("Wait for Target 1 to finish (15 iterations)"));
		th->Join();
		Console::WriteLine(new String("Finished"));
	}
Exemplo n.º 25
0
	void Audio::Play2D(bool spawnThread)
	{
		Play2DStruct *data = new Play2DStruct();
		data->audio = this;

		if(spawnThread)
		{
			Thread *thread = new Thread(Audio::Play2DProcess);
			data->thread = thread;
			thread->Start(data);
		}
		else
			Play2DProcess(data);
	}
Exemplo n.º 26
0
int main(int argc, char** argv)
{
	const int N = 1;
	for (int i = 0; i < N; ++i)
	{
		Thread thread;
		thread.Init();
		thread.Start(func, NULL);		
	} 	
	while(1)
	{
		sleep(1);
	}
	return 0;
}
Exemplo n.º 27
0
void SuiteThreadStartDelete::Test()
{
    PrioSaw ps(kPrioritySystemLowest, kPrioritySystemHighest);

    for (TUint i=0; i< kThreadCount; i++) {
        Thread* th = new ThreadDummy(ps.Next());
        th->Start();
        delete th;

        if (i % kUpdateInterval == 0) {
            TEST(true); // only to show progress
            Thread::Sleep(100); // FreeRTOS delegates freeing of thread resources to the idle thread. We allow it to run here.
        }
    }
}
Exemplo n.º 28
0
      /**
       * \brief Test the cancelation of thread. 
       */
      void testThreadCancel()
      {
        void* ret = NULL;
        Callback obj;
        Thread th = Thread(new ThreadArgImpl<Callback>(obj, &Callback::Call2, NULL));

        th.Start(false);
        th.Stop();
        th.Join(&ret);
        
        /* on x86 it returns 0xffffffff
         * on x86-64 0xffffffffffffffff
         * so (void*)-1
         */
        CPPUNIT_ASSERT(ret == (void*)-1);
      }
Exemplo n.º 29
0
int ThreadPool::Start(int threadCount, Runnable& target) {
	//XXX
	//不Clear的话,可以同一个ThreadPool执行不同的Target
	//threads.clear();
	for(int i = 0; i < threadCount; i++){
		Thread* tmpThread = new Thread(target);
		int ret = tmpThread->Start();
		if (ret){
			printf("Create thread number : %d\n", (int)i);
			return i;
		}
		threads.push_back(tmpThread);
	}
//	puts("Create thread pool succeful");
	return 0;
}
Exemplo n.º 30
0
ThreadPool::ThreadPool(int threadCount) :
    mThreadCount(threadCount),
    mThreadList(),
    mTaskList(),
    mMutex(),
    mGetTaskCV(),
    mFinishTaskCV(),
    mTaskLeftCount(0)
{
    for (int tid = 0; tid < mThreadCount; tid++)
    {
        Thread* pThread = new Thread(this);
        pThread->Start();
        mThreadList.push_back(pThread);
    }
}