Ejemplo n.º 1
0
void VDFileAsync9x::Open(const wchar_t *pszFilename, uint32 count, uint32 bufferSize) {
	try {
		mFilename = VDTextWToA(pszFilename);

		const DWORD slowFlags = mbWriteThrough ? FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH : FILE_ATTRIBUTE_NORMAL;

		mhFileSlow = CreateFileA(mFilename.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, slowFlags, NULL);
		if (mhFileSlow == INVALID_HANDLE_VALUE)
			throw MyWin32Error("Unable to open file \"%s\" for write: %%s", GetLastError(), mFilename.c_str());

		if (mbUseFastMode)
			mhFileFast = CreateFileA(mFilename.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL);

		mSectorSize = 4096;		// guess for now... proper way would be GetVolumeMountPoint() followed by GetDiskFreeSpace().

		mBlockSize = bufferSize;
		mBlockCount = count;
		mBuffer.Init(count * bufferSize);

		mState = kStateNormal;
	} catch(const MyError&) {
		Close();
		throw;
	}

	ThreadStart();
}
Ejemplo n.º 2
0
void VDFileAsyncNT::Open(VDFileHandle h, uint32 count, uint32 bufferSize) {
	try {
		mFilename = "<anonymous pipe>";

		HANDLE hProcess = GetCurrentProcess();
		if (!DuplicateHandle(hProcess, h, hProcess, &mhFileSlow, 0, FALSE, DUPLICATE_SAME_ACCESS))
			throw MyWin32Error("Unable to open file \"%s\" for write: %%s", GetLastError(), mFilename.c_str());

		mSectorSize = 4096;		// guess for now... proper way would be GetVolumeMountPoint() followed by GetDiskFreeSpace().

		mBlockSize = bufferSize;
		mBlockCount = count;
		mBufferSize = mBlockSize * mBlockCount;

		mWriteOffset = 0;
		mBufferLevel = 0;

		mState = kStateNormal;

		if (mhFileFast != INVALID_HANDLE_VALUE) {
			mpBlocks = new VDFileAsyncNTBuffer[count];
			mBuffer.resize(count * bufferSize);
			ThreadStart();
		}
	} catch(const MyError&) {
		Close();
		throw;
	}
}
Ejemplo n.º 3
0
void VDFileAsyncNT::Open(const wchar_t *pszFilename, uint32 count, uint32 bufferSize) {
	try {
		mFilename = VDTextWToA(pszFilename);

		mhFileSlow = CreateFileW(pszFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (mhFileSlow == INVALID_HANDLE_VALUE)
			throw MyWin32Error("Unable to open file \"%s\" for write: %%s", GetLastError(), mFilename.c_str());

		mhFileFast = CreateFileW(pszFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, NULL);
		if (mhFileFast == INVALID_HANDLE_VALUE)
			mhFileFast = CreateFileW(pszFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED, NULL);

		mSectorSize = 4096;		// guess for now... proper way would be GetVolumeMountPoint() followed by GetDiskFreeSpace().

		mBlockSize = bufferSize;
		mBlockCount = count;
		mBufferSize = mBlockSize * mBlockCount;

		mWriteOffset = 0;
		mBufferLevel = 0;

		mState = kStateNormal;

		if (mhFileFast != INVALID_HANDLE_VALUE) {
			mpBlocks = new VDFileAsyncNTBuffer[count];
			mBuffer.resize(count * bufferSize);
			ThreadStart();
		}
	} catch(const MyError&) {
		Close();
		throw;
	}
}
Ejemplo n.º 4
0
bool VDCallbackTimer::Init3(IVDTimerCallback *pCB, uint32 period_100ns, uint32 accuracy_100ns, bool precise) {
	Shutdown();

	mpCB = pCB;
	mbExit = false;
	mbPrecise = precise;

	UINT accuracy = accuracy_100ns / 10000;
	if (accuracy > 10)
		accuracy = 10;

	TIMECAPS tc;
	if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof tc)) {
		if (accuracy < tc.wPeriodMin)
			accuracy = tc.wPeriodMin;
		if (accuracy > tc.wPeriodMax)
			accuracy = tc.wPeriodMax;
	}

	if (TIMERR_NOERROR == timeBeginPeriod(accuracy)) {
		mTimerAccuracy = accuracy;
		mTimerPeriod = period_100ns;
		mTimerPeriodAdjustment = 0;
		mTimerPeriodDelta = 0;

		if (ThreadStart())
			return true;
	}

	Shutdown();

	return false;
}
Ejemplo n.º 5
0
CPdd6410Uart::~CPdd6410Uart()
{
    InitModem(FALSE);
    if (m_hISTEvent)
    {
        m_bTerminated=TRUE;
        ThreadStart();
        SetEvent(m_hISTEvent);
        ThreadTerminated(1000);
        InterruptDisable( m_dwSysIntr );         
        CloseHandle(m_hISTEvent);
    };
    if (m_pReg6410Uart)
    {
        delete m_pReg6410Uart;
    }
    if (m_XmitFlushDone)
    {
        CloseHandle(m_XmitFlushDone);
    }
    if (m_pRegVirtualAddr != NULL)
    {
        MmUnmapIoSpace((PVOID)m_pRegVirtualAddr,sizeof(S3C6410_UART_REG));
    }        
}
Ejemplo n.º 6
0
void CPdd6410Uart::PostInit()
{
    DWORD dwCount=0;
    m_HardwareLock.Lock();
    m_pReg6410Uart->Write_UCON(0); // Set to Default;
    DisableInterrupt(S6410UART_INT_RXD | S6410UART_INT_TXD | S6410UART_INT_ERR | S6410UART_INT_MODEM);
    // Mask all interrupt.
    while ((GetInterruptStatus() & (S6410UART_INT_RXD | S6410UART_INT_TXD | S6410UART_INT_ERR | S6410UART_INT_MODEM))!=0 && dwCount <MAX_RETRY)
    {
        InitReceive(TRUE);
        InitLine(TRUE);
        ClearInterrupt(S6410UART_INT_RXD | S6410UART_INT_TXD | S6410UART_INT_ERR | S6410UART_INT_MODEM);
        dwCount++;
    } 
    ASSERT((GetInterruptStatus() & (S6410UART_INT_RXD | S6410UART_INT_TXD | S6410UART_INT_ERR | S6410UART_INT_MODEM))==0);
    m_HardwareLock.Unlock();
    CSerialPDD::PostInit();
    CeSetPriority(m_dwPriority256);
#ifdef DEBUG
    if ( ZONE_INIT )
    {
        m_pReg6410Uart->DumpRegister();
    }
#endif
    ThreadStart();  // Start IST.
}
Ejemplo n.º 7
0
/*------------------------------------------------------------------------
       Parameters:

      Description:

    Return Values:
            0 on success, < 0 otherwise.

------------------------------------------------------------------------*/
int
WinCreate(char *pcName, int button_rows, int image_rows, int image_cols,
          int rows, int cols)
{
  int    iWin ;
  DIAG_WINDOW *pwin ;

  iWin = winNewHandle() ;
  if (iWin < 0)
    return(ErrorPrintf(ERROR_NO_MEMORY,
                       "WinAlloc: could not allocate new window"));

  pwin = HandleToPtr(iWin) ;
  pwin->xvf = XValloc(rows, cols, button_rows, image_rows, image_cols,
                      pcName, winPoll) ;
  XVsetParms(event_handler) ;

  if (!inited)
  {
    ThreadInit(0, MAX_WINDOWS, 10*1024, 1) ;
    inited = 1 ;
  }

  ThreadStart("window", winThread, pwin, MIN_PRIORITY) ;

  ThreadSuspend(TID_SELF, SIG_ANY) ;
  WinFlush(iWin) ;
  return(iWin) ;
}
Ejemplo n.º 8
0
/*****************for gps power ctl*********************/
CSerialPDDPowerUpCallback::CSerialPDDPowerUpCallback(CSerialPDD * pSerialObj)
:   m_pSerialObj(pSerialObj)
,   CMiniThread (0, TRUE)
{
    DEBUGCHK(m_pSerialObj!=NULL);
    m_hEvent =CreateEvent(NULL,FALSE,FALSE,NULL);
    ThreadStart();
}
Ejemplo n.º 9
0
Worker* NewWorker(char* pipeName, aio4c_size_t bufferSize) {
    Worker* worker = NULL;
    ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER;

    if ((worker = aio4c_malloc(sizeof(Worker))) == NULL) {
#ifndef AIO4C_WIN32
        code.error = errno;
#else /* AIO4C_WIN32 */
        code.source = AIO4C_ERRNO_SOURCE_SYS;
#endif /* AIO4C_WIN32 */
        code.size = sizeof(Worker);
        code.type = "Worker";
        Raise(AIO4C_LOG_LEVEL_ERROR, AIO4C_ALLOC_ERROR_TYPE, AIO4C_ALLOC_ERROR, &code);
        return NULL;
    }

    worker->queue      = NULL;
    worker->pool       = NULL;
    worker->writer     = NULL;
    worker->bufferSize = bufferSize;

    if (pipeName != NULL) {
        worker->pipe       = pipeName;
        worker->name       = aio4c_malloc(strlen(pipeName) + 1 + 7);
        if (worker->name != NULL) {
            snprintf(worker->name, strlen(pipeName) + 1 + 7, "%s-worker", pipeName);
        }
    } else {
        worker->pipe = NULL;
        worker->name = NULL;
    }

    worker->thread = NewThread(
            worker->name,
            _WorkerInit,
            _WorkerRun,
            _WorkerExit,
            (ThreadData)worker);

    if (worker->thread == NULL) {
        if (worker->name != NULL) {
            aio4c_free(worker->name);
        }
        aio4c_free(worker);
        return NULL;
    }

    if (!ThreadStart(worker->thread)) {
        if (worker->name != NULL) {
            aio4c_free(worker->name);
        }
        aio4c_free(worker);
        return NULL;
    }

    return worker;
}
Ejemplo n.º 10
0
  void BuildQueueInit(BuildQueue* queue, const BuildQueueConfig* config)
  {
    CHECK(config->m_MaxExpensiveCount > 0 && config->m_MaxExpensiveCount <= config->m_ThreadCount);

    MutexInit(&queue->m_Lock);
    CondInit(&queue->m_WorkAvailable);

    // Compute queue capacity. Allocate space for a power of two number of
    // indices that's at least one larger than the max number of nodes. Because
    // the queue is treated as a ring buffer, we want W=R to mean an empty
    // buffer.
    uint32_t capacity = NextPowerOfTwo(config->m_MaxNodes + 1);

    MemAllocHeap* heap = config->m_Heap;

    queue->m_Queue              = HeapAllocateArray<int32_t>(heap, capacity);
    queue->m_QueueReadIndex     = 0;
    queue->m_QueueWriteIndex    = 0;
    queue->m_QueueCapacity      = capacity;
    queue->m_Config             = *config;
    queue->m_PendingNodeCount   = 0;
    queue->m_FailedNodeCount    = 0;
    queue->m_QuitSignalled      = false;
    queue->m_ExpensiveRunning   = 0;
    queue->m_ExpensiveWaitCount = 0;
    queue->m_ExpensiveWaitList  = HeapAllocateArray<NodeState*>(heap, capacity);

    CHECK(queue->m_Queue);

    if (queue->m_Config.m_ThreadCount > kMaxBuildThreads)
    {
      Log(kWarning, "too many build threads (%d) - clamping to %d",
          queue->m_Config.m_ThreadCount, kMaxBuildThreads);

      queue->m_Config.m_ThreadCount = kMaxBuildThreads;
    }

    Log(kDebug, "build queue initialized; ring buffer capacity = %u", queue->m_QueueCapacity);

    // Block all signals on the main thread.
    SignalBlockThread(true);
    SignalHandlerSetCondition(&queue->m_WorkAvailable);

    // Create build threads.
    for (int i = 0, thread_count = config->m_ThreadCount; i < thread_count; ++i)
    {
      ThreadState* thread_state = &queue->m_ThreadState[i];

      ThreadStateInit(thread_state, queue, MB(64), MB(32), i);

      if (i > 0)
      {
        Log(kDebug, "starting build thread %d", i);
        queue->m_Threads[i] = ThreadStart(BuildThreadRoutine, thread_state);
      }
    }
  }
PyrideRemoteDataHandler::PyrideRemoteDataHandler(void) :
  robotID_( -1 )
{
  ConsoleDataProcessor::instance()->init( this );

  Thread ^ dataThread = gcnew Thread( gcnew ThreadStart( &PyrideRemoteDataHandler::DataThreadProc ) );
  dataThread->IsBackground = true;
  dataThread->Start();
}
Ejemplo n.º 12
0
void HiloControl::iniciarHilo()
{
	hilo = gcnew Thread(gcnew ThreadStart(this, &HiloControl::metodoHilo));
	hilo->Start();

	/*while (!myThread->IsAlive);   // wait for the thread to start
	Thread::Sleep(100);
	*/
}
Ejemplo n.º 13
0
void __fastcall TConfDlg::RefreshButtonClick(TObject *Sender)
{

    TMessage m;
    m.Msg=REFRESH_START;
    Incomplete=true;
    if(!Servers->Refresh()) {
    	ThreadStart(m);
    } else Incomplete=false;
}
Ejemplo n.º 14
0
BOOL CSDWorkItem::Init(DWORD  dwCeThreadPriority)
{
    if (m_psdSlotEvent!=NULL && m_hWakeupEvent!=NULL && m_hEmptySlotSem!=NULL) {
         CeSetPriority( (int)dwCeThreadPriority );
         ThreadStart();
         return TRUE;
    };
    ASSERT(FALSE);
    return FALSE;
    
}
void VideoStreamController::processVideoStream( bool isStart )
{
  isStreaming_ = isStart;

  if (isStreaming_) {
      // start thread to grab.
    Thread ^ dataThread = gcnew Thread( gcnew ThreadStart( this, &VideoStreamController::dataThreadProc ) );
    dataThread->IsBackground = true;
    dataThread->Start();
  }
}
Ejemplo n.º 16
0
///////////////////////////////////////////////////////////////////////////////
//  ~CSDWorkItem - destructor
//  Input:  
//  Output: 
//  Notes:  
//      
///////////////////////////////////////////////////////////////////////////////
CSDWorkItem::~CSDWorkItem() 
{

    m_bTerminated = TRUE;
    ThreadStart();
    if ( m_hWakeupEvent )
        SetEvent(m_hWakeupEvent);
    BOOL fRet = WaitThreadComplete( 5000 );
    ASSERT(fRet);
    if (m_hEmptySlotSem!=NULL)
        CloseHandle(m_hEmptySlotSem);
    if (m_hWakeupEvent!=NULL)
        CloseHandle(m_hWakeupEvent);
    delete m_psdSlotEvent;
}
Ejemplo n.º 17
0
/******************************************************************************
    处理名        :  启动处理
    函数名        :  Start()
    参数          :  无
    返回值        :  无
******************************************************************************/
int CChannelItem::Start(){
    printfs(1, "<CChannelItem>Start command received!");
    if(m_bStarted) {
        return 0;
    }
    /* 生成各个子线程的处理类                                                */
    if(CreateProcess() < 0) {
        m_bCanStart = false;
        return -1;
    } 
    /* 生成各个子线程                                                        */
    ThreadCreate();
    /* 启动各个子线程                                                        */
    ThreadStart();
    m_bStarted = true;
    return 0;
}
Ejemplo n.º 18
0
BOOL CSocketSelectDlg::OnWmInitdialog(WPARAM wParam, LPARAM lParam)
{
  HRESULT hResult;

  m_hCurDev = INVALID_HANDLE_VALUE;
  m_lCtrlNo = -1;

  UpdateView(NULL);
  DeviceListClear();

  //
  // initialize the device list and a thread that waits on
  // the change event from the device enumerator
  //
  hResult = ThreadStart();

  vciDisplayError(CDialogWnd::GetHandle(), NULL, hResult);

  return(TRUE);
}
Ejemplo n.º 19
0
bool WindowsHttpDownloader::StartAsync(const char* url, const char* append_headers)
{
	int len = strlen(url);
	if (len < 8 || len > 2047)
		return false;

	_urls[0] = 0;
	AnsiToUnicode(url, _urls, _countof(_urls));
	RtlZeroMemory(&_url, sizeof(_url));
	_url.dwStructSize = sizeof(_url);
	_url.dwUrlPathLength =
		_url.dwHostNameLength =
		_url.dwExtraInfoLength =
		_url.dwUserNameLength =
		_url.dwPasswordLength =
		_url.dwSchemeLength = -1;
	if (!WinHttpCrackUrl(_urls, 0, 0, &_url))
		return false;
	return ThreadStart(append_headers ? strdup(append_headers) : NULL);
}
Ejemplo n.º 20
0
	// -- Init / Shutdown --
	void WorkerThread::Make(WorkerThreadPool * pool, uint32 threadIndex)
	{
		//BOOST_LOG( gn_log::get() ) << "(Concurrent) \tWorker[ " << threadIndex << " ] starting up...\n";
		LogInfo("WorkerThread[%i] starting up...", threadIndex);
		
		Index_ = threadIndex;
		Pool_ = pool;
		TaskMutex_.reset( MutexCreate(AllocatorGetHeap()) );
		Tasks_.reserve(TaskCapacity);	// some random number of tasks
		
		if(Index_ != 0)	// so long as we're not the main thread...
		{
			//Thread_ = boost::thread( boost::bind( &Worker::Run, this ) );	// create the boost::thread to run our shit
			ThreadFunction runFn = MakeDelegate(this, &WorkerThread::Run);

			Thread_.reset( ThreadCreate(AllocatorGetHeap()) );
			ThreadStart(Thread_, runFn, nullptr);
		}
		// TODO: Fix this.
		else	// Set this here, as the Run() function, which sets it otherwise, won't get called.
			LocalWorkerThread_ = this;
			//ThisThread_.reset( (const_cast<Worker *>(this)) );
	}
Ejemplo n.º 21
0
bool VDAudioOutputDirectSoundW32::Init(uint32 bufsize, uint32 bufcount, const tWAVEFORMATEX *wf, const wchar_t *preferredDevice) {
	mBufferSize = bufsize * bufcount;
	mBuffer.resize(mBufferSize);
	mBufferReadOffset = 0;
	mBufferWriteOffset = 0;
	mBufferLevel = 0;

	if (wf->wFormatTag == WAVE_FORMAT_PCM) {
		mInitFormat.resize(sizeof(tWAVEFORMATEX));
		memcpy(&*mInitFormat, wf, sizeof(PCMWAVEFORMAT));
		mInitFormat->cbSize = 0;
	} else
		mInitFormat.assign(wf, sizeof(tWAVEFORMATEX) + wf->cbSize);

	mMutex.Lock();
	mbThreadInited = false;
	mbThreadInitSucceeded = false;
	mMutex.Unlock();

	if (!ThreadStart())
		return false;

	mMutex.Lock();
	while(!mbThreadInited) {
		mMutex.Unlock();
		HANDLE h[2] = { getThreadHandle(), mUpdateEvent.getHandle() };

		if (WaitForMultipleObjects(2, h, FALSE, INFINITE) != WAIT_OBJECT_0 + 1)
			break;

		mMutex.Lock();
	}
	bool succeeded = mbThreadInitSucceeded;
	mMutex.Unlock();

	return succeeded;
}
Ejemplo n.º 22
0
int MQTTStartTask(MQTTClient *client)
{
    return ThreadStart(&client->thread, &MQTTRun, client);
}
Ejemplo n.º 23
0
Reader* NewReader(char* pipeName, aio4c_size_t bufferSize) {
    Reader* reader = NULL;
    ErrorCode code = AIO4C_ERROR_CODE_INITIALIZER;

    if ((reader = aio4c_malloc(sizeof(Reader))) == NULL) {
#ifndef AIO4C_WIN32
        code.error = errno;
#else /* AIO4C_WIN32 */
        code.source = AIO4C_ERRNO_SOURCE_SYS;
#endif /* AIO4C_WIN32 */
        code.size = sizeof(Reader);
        code.type = "Reader";
        Raise(AIO4C_LOG_LEVEL_ERROR, AIO4C_ALLOC_ERROR_TYPE, AIO4C_ALLOC_ERROR, &code);
        return NULL;
    }

    reader->selector   = NULL;
    reader->queue      = NULL;
    reader->worker     = NULL;
    reader->bufferSize = bufferSize;
    reader->load       = 0;

    if (pipeName != NULL) {
        reader->pipe       = pipeName;
        reader->name       = aio4c_malloc(strlen(pipeName) + 1 + 7);
        if (reader->name != NULL) {
            snprintf(reader->name, strlen(pipeName) + 1 + 7, "%s-reader", pipeName);
        }
    } else {
        reader->pipe = NULL;
        reader->name = NULL;
    }

    reader->thread = NewThread(
            reader->name,
           _ReaderInit,
           _ReaderRun,
           _ReaderExit,
           (ThreadData)reader);

    if (reader->thread == NULL) {
        FreeSelector(&reader->selector);
        if (reader->pipe != NULL) {
            aio4c_free(reader->pipe);
        }
        if (reader->name != NULL) {
            aio4c_free(reader->name);
        }
        aio4c_free(reader);
        return NULL;
    }

    if (!ThreadStart(reader->thread)) {
        FreeSelector(&reader->selector);
        if (reader->pipe != NULL) {
            aio4c_free(reader->pipe);
        }
        if (reader->name != NULL) {
            aio4c_free(reader->name);
        }
        aio4c_free(reader);
        return NULL;
    }

    return reader;
}
Ejemplo n.º 24
0
Archivo: SOCKET.cpp Proyecto: tiku/test
int WSA_Async::Recv(ASYNC_CALLBACK call){
	ThreadStart(call);
	return 0;
}
Ejemplo n.º 25
0
System::Void Communication::WorkThread() {

	isWorkThreadRunning = true;
	isListenThreadRunning = true;
	isSendThreadRunning = true;
	isCommunicationThreadRunning = true;
	this->isDownloaderCommunicationThreadRunning = true;
	// Start the listening thread.
	ThreadStart ^ listenThreadStart = gcnew ThreadStart(this, &Communication::ListenThread);
	listenThread = gcnew Thread(listenThreadStart);
	listenThread->Name = L"ListenThread";
	listenThread->Priority = ThreadPriority::BelowNormal;
	listenThread->Start();
	ThreadStart^ sendThreadStart = gcnew ThreadStart(this,&Communication::SendThread);
	sendThread = gcnew Thread(sendThreadStart);
	sendThread->Name = L"SendThread";
	sendThread->Start();
	ThreadStart ^ communicationThreadStart = gcnew ThreadStart(this, &Communication::CommunicationThread);
	communicationThread = gcnew Thread(communicationThreadStart);
	communicationThread->Name = L"CommunicationThread";
	communicationThread->Start();
	ThreadStart ^ downloaderCommunicationThreadStart = gcnew ThreadStart(this, &Communication::DownloaderCommunicationThread);
	downloaderCommunicatonThread = gcnew Thread(downloaderCommunicationThreadStart);
	downloaderCommunicatonThread->Name = L"DownloaderCommunicationThread";
	downloaderCommunicatonThread->Start();

	int32_t ioTaskTimeEclipsed = 0;
	OusnsMessage^ currentMsg;
	DateTime currentTime;
	//DateTime^ afterJobTime;
	int timeUsedForJob = 0;
	while (isWorkThreadRunning) {
		Thread::Sleep(THREAD_SLEEP_TIME);
		currentTime = DateTime::Now;
		if (this->workQueue->Count > 0) {
			if (DEBUG_WORK_THREAD) {
				MessageBox::Show("=WORK=\nWork found in queue! Do work.");
			}
			//Get the first element of queue in monitor condition
			try {
				Threading::Monitor::Enter(workQueueLock);
				currentMsg = this->workQueue->Last->Value;
				this->workQueue->RemoveLast();
				Threading::Monitor::Exit(workQueueLock);
			} 
			catch (ThreadAbortException^ ){
				//Threading::Monitor::Exit(workQueueLock);
			}
			catch (Exception ^ e) {
				MessageBox::Show("Exception in lock:WorkThread: " + e->ToString());
				Threading::Monitor::Exit(workQueueLock);
			}
			//Start processing the message
			try{
				this->ProcessMessage(currentMsg);
			}
			catch (Exception ^ e) {
				if (DEBUG_WORK_THREAD) {
					MessageBox::Show("Exception in lock:WorkThread: " + e->ToString());
				}
			}		
		}
Ejemplo n.º 26
0
//--
#include "recorder.h"

namespace Timok_IVR {
Recorder::Recorder(Card^ pCard, int pModuleNumber, int pChannelNumber, IVRLogger^ pLogger) {
	card = pCard;
	module_number = pModuleNumber;
	call_number = pChannelNumber;
	logger = pLogger;

	record_parms = new SM_FILE_RECORD_PARMS();

	thread_start = gcnew ThreadStart(this, &Recorder::thread);
	worker_thread = gcnew Thread(thread_start);
}

Recorder::~Recorder() { 
	delete record_parms;
}

void Recorder::Record(long pChannelId, String^ pFile_path, int pTimeLimit) {
	Channel_id = pChannelId;
	file_to_record = pFile_path;
	time_limit = pTimeLimit * 1000;

	Is_complete = false;
	Should_abort = false;

	worker_thread->Start();
}
Ejemplo n.º 27
0
int main(int argc, char** argv)
{
	if (argc < 2)
		return usage(argc, argv);

	parent = pthread_self();
	sigset_t original, masking;
	sigemptyset(&original);
	sigemptyset(&masking);
	sigaddset(&masking, SIGUSR1);
	pthread_sigmask(SIG_SETMASK, &masking, &original);

	int wakeupThreads = 0;
	try
	{
		wakeupThreads = lexicalCast<int>(argv[argc-1]);
		if (wakeupThreads < 1)
			return usage(argc, argv);

		std::cout << "wakeup threads of " << wakeupThreads << std::endl;
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return usage(argc, argv);
	}

	void* handle = WWWInit();
	std::vector<Item> items = loadItems();
	resetItems(items);
	void* filterManagerContext = FilterManagerCreate(NULL);

	std::map<void*, void*> contextMap;
	

	// create threads.
	for (int count = 0; count != wakeupThreads; ++count)
	{
		std::vector<Item>::iterator itor = find_uncheck_item(items);
		if (itor == items.end())
			break;

		itor->check_flg = true;
		void* thread = ThreadCreate();
		void* httpContext = HTTPCreateContext(itor->url_check.c_str(),
											  NULL, NULL, 20);
		contextMap[thread] = httpContext;
		std::cout << "thread: " << thread <<
			"   context: " << httpContext << std::endl;
		ThreadStart(thread, httpContext, handler);
	}

	try
	{
		std::vector<Item>::iterator itor;
		while ((itor = find_uncheck_item(items)) != items.end())
		{
			itor->check_flg = true;
			
			int signalNum = 0;
			sigwait(&masking, &signalNum);
			if (signalNum == SIGUSR1)
			{
				// signal一回で複数の待ちハンドラを処理した方が良さそう
				ScopedLock<Mutex> lock(syncObject);
				assert (idleThreads.size() > 0);
				void* thread = idleThreads.back();
				idleThreads.pop_back();
				ThreadJoin(thread);

				void* httpContext = contextMap[thread];
				assert(httpContext != NULL);
				contextMap[thread] = NULL;

				{
					char url[2048];
					url[HTTPGetURL(httpContext, url, sizeof(url))] = 0;
					std::vector<Item>::iterator item_itor =
						find_item_from_url(items, url);

					if (item_itor == items.end())
						throw std::runtime_error((std::string("unfind URL: ") +
												  url).c_str());

					char date[256];
					date[HTTPGetLastModified(httpContext,
											 date, sizeof(date))] = 0;
					item_itor->last_updated = date;

					item_itor->crc32 = HTTPGetFilteredCRC32(httpContext,
													   filterManagerContext);
				
					item_itor->content_length =
						HTTPGetContentsLength(httpContext);

					HTTPClose(httpContext);
				}
				HTTPCreateContext(itor->url_check.c_str(),
								  NULL, NULL, 20);
				contextMap[thread] = httpContext;
				std::cout << "thread: " << thread <<
					"   context: " << httpContext << std::endl;
				ThreadStart(thread, httpContext, handler);
			}
		}

		// 稼働中のスレッドがwakeupThreads個存在する
		for (int count = 0; count != wakeupThreads; ++count)
		{
			int signalNum = 0;
			// signal一回で複数の待ちハンドラを処理した方が良さそう
			sigwait(&masking, &signalNum);
			ScopedLock<Mutex> lock(syncObject);
			ThreadClose(idleThreads.back());
			idleThreads.pop_back();
		}
	}
	catch (std::exception& e)
	{
		std::cerr << "raise exception: " << e.what() << std::endl;
	}
	catch (...)
	{
		std::cerr << "unknown exception raised." << std::endl;
	}

	saveItems(items);
	FilterManagerTerminate(filterManagerContext);
	WWWTerminate(handle);
	pthread_sigmask(SIG_SETMASK, &original, NULL);

	return 0;
}
Ejemplo n.º 28
0
bool ServerStart(Server* server) {
    return ThreadStart(server->thread);
}
Ejemplo n.º 29
0
		for each(AxisCtlProtoStuct protocalData in dataQueue)
		{
			if (protocalData.id >= 0x700)
			{
				if (protocalData.id != 0x700 && protocalData.id != 0x703 && protocalData.id != 0x100 && protocalData.id != 0x7A0 && protocalData.id != 0x7F0 && protocalData.id != 0x7F1 && protocalData.id != 0x7F2)
				{
					//Console::WriteLine("collimator {0}", protocalData.id);
				}
			}

			switch (protocalData.id)
			{
			case 0x700:
			{
				 if (protocalData.isRemote)
				 {
					 List<AxisCtlProtoStuct> ^ sendBuffer = gcnew List<AxisCtlProtoStuct>;
					 ASR1ModelMsgPS ^ response = gcnew ASR1ModelMsgPS;
					 response->MODEL = asr1Model;
					 sendBuffer->Add(response->GetFrame());
					 canBus->Send(sendBuffer);
				 }
			}
				break;

			case 0x703:
			{
				 if (protocalData.isRemote)
				{
					 List<AxisCtlProtoStuct> ^ sendBuffer = gcnew List<AxisCtlProtoStuct>;
					 ASR1SNMsgPS ^ response = gcnew ASR1SNMsgPS;
					 response->SN = asr1SN;
					 AxisCtlProtoStuct frame1 = response->GetFrame();
					 sendBuffer->Add(response->GetFrame());
					 canBus->Send(sendBuffer);


				}
			}
				break;

			case 0x7A6:
			{
						  if (protocalData.isRemote)
						  {
							  List<AxisCtlProtoStuct> ^ sendBuffer = gcnew List<AxisCtlProtoStuct>;
							  ASR2ModelMsgPS ^ response = gcnew ASR2ModelMsgPS;
							  response->MODEL = asr2Model;
							  sendBuffer->Add(response->GetFrame());
							  canBus->Send(sendBuffer);
						  }
			}
				break;

			case 0x7A0:
			{
						  ASR2CtlMsgPS ^ requeset = gcnew ASR2CtlMsgPS(protocalData);
						  opMode = requeset->MODE;
						  crossBladeSize = requeset->CROSS_SIZE;
						  longBladeSize = requeset->LONG_SIZE;
						  lampOn = requeset->LAMP_ON;
						  vSid = requeset->V_SID;
			}
				break;

			case 0x702:
			//	Console::WriteLine("{0}", protocalData.id);
				{
					ASR2Ctl2MsgPS ^ request = gcnew ASR2Ctl2MsgPS(protocalData);

					if (request->LASER_ON)
					{
						lampOn = true;
					}
					if (request->LASER_OFF)
					{
						lampOn = false;
					}
					if (request->IS_LAMPCYCLE)
					{
						ThreadStart ^ lampThreadStart = gcnew ThreadStart(this,&CollimatorCLS::LampCycleFunc);
						Thread ^ lampThread = gcnew Thread(lampThreadStart);
						lampThread->IsBackground = true;
						lampThread->Start();
					}
				}
			default:
				break;
			}
		}
Ejemplo n.º 30
0
	MessageBox::Show("¬рем¤ выполнени¤: " + time.ToString() + " мс");
	pbRun->Value = 0;
	writer->Close();
	output->Close();
	pbRun->Value = 0;
	btnTask1->Enabled = true;
	btnTask2->Enabled = true;
	btnTask3->Enabled = true;
}

System::Void MainForm::btnTask1_Click(System::Object ^ sender, System::EventArgs ^ e)
{
	if (primesThread) {
		delete primesThread;
	}
	primesThread = gcnew Thread(gcnew ThreadStart(this, &MainForm::Primes));
	primesThread->Start();
}

System::Void MainForm::btnTask2_Click(System::Object ^ sender, System::EventArgs ^ e)
{
	array<int> ^intervals = gcnew array<int>(30);
	for (int i = 0; i < 30; i++) {
		intervals[i] = 0;
	}
	for (int i = 0; i < count - 1; i++) {
		if ((primes[i + 1] - primes[i]) > intervals[0]) {
			intervals[0] = primes[i + 1] - primes[i];
			intervals->Sort(intervals);
		}
	}