Ejemplo n.º 1
0
DWORD FileProcessor::Run(LPVOID /*arg*/)
{
	if( PP ){
	 FileEntry entry;
		nProcessed = 0;
		while( !PP->quitRequested() && (isBackwards ? PP->getBack(entry) : PP->getFront(entry)) ){
		 // create a scoped lock without closing it immediately
		 CRITSECTLOCK::Scope scp(PP->ioLock, 0);
			scope = &scp;
			currentEntry = &entry;
			_InterlockedIncrement(&PP->nProcessing);
			entry.compress( this, PP );
			_InterlockedDecrement(&PP->nProcessing);
			_InterlockedIncrement(&PP->nProcessed);
			currentEntry = NULL;
			nProcessed += 1;
			scope = NULL;

			runningTotalRaw += entry.fileInfo.st_size;
			runningTotalCompressed += (entry.compressedSize > 0)? entry.compressedSize : entry.fileInfo.st_size;
			/*if( PP->verbose() > 1 )*/{
#if defined(__MACH__)
                mach_port_t thread = mach_thread_self();
				mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
				thread_basic_info_data_t info;
				int kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);
				if( kr == KERN_SUCCESS ){
					 userTime = info.user_time.seconds + info.user_time.microseconds * 1e-6;
					 systemTime = info.system_time.seconds + info.system_time.microseconds * 1e-6;
					 avCPUUsage += info.cpu_usage * 100.0 / TH_USAGE_SCALE;
					 threadInfo = info;
					 hasInfo = true;
				}
				mach_port_deallocate(mach_task_self(), thread);
#elif defined(linux)
				struct rusage rtu;
				if (!getrusage(RUSAGE_THREAD, &rtu)) {
					const auto ut = rtu.ru_utime.tv_sec + rtu.ru_utime.tv_usec * 1e-6;
					const auto st = rtu.ru_stime.tv_sec + rtu.ru_stime.tv_usec * 1e-6;
					if (ut >= 0 && st >= 0) {
						userTime = ut, systemTime = st, hasInfo = true;
					}
				}
#	ifdef CLOCK_THREAD_CPUTIME_ID
				struct timespec ts;
				if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) != -1) {
					cpuTime = ts.tv_sec + ts.tv_nsec * 1e-9;
					double t = userTime + systemTime;
					if (cpuTime > 0) {
						avCPUUsage += t * 100.0 / cpuTime;
					}
				}
#	endif
#endif
			}
		}
	}
	return DWORD(nProcessed);
}
int output_data_into_parallel_port(unsigned char* buf, unsigned buf_size)
{
	int ret_code = 0x0;
	unsigned char cmd = 0x0;
	unsigned long ip_addr = 0x0;
	APPLICATION_ENVIRONMENT::IP_TABLE_MAP_ITER itr;
	APPLICATION_ENVIRONMENT::DEVICE_INFO_LIST::iterator di_itr;
	unsigned char virtual_buf[256] = {0};
	SOCKADDR_IN ip = {0};

	memcpy(&ip_addr, buf + 16, sizeof(unsigned long));
	
	itr = __application_environment.virtual_ip_table_map_->find(ip_addr);
	if(itr != __application_environment.virtual_ip_table_map_->end()){

		_InterlockedIncrement(&__application_environment.upd_send_num_);
		udp_send((const char*)buf, buf_size);
	}
	else{

		//主机IP设置广播 & 响应主机IP设置
		cmd = *(buf + 0x20);
		memcpy(&ip_addr, buf + 21, sizeof(unsigned long));
		if(cmd == 0x1){
			for(di_itr = __application_environment.device_info_list_->begin();
				di_itr != __application_environment.device_info_list_->end(); ++di_itr){
				
				if((*di_itr)->sn_ == ip_addr) break;
			}

			if(di_itr == __application_environment.device_info_list_->end()) return 0;

			if(!(*di_itr)->is_be_virtual_fdu_){	(*di_itr)->ip_ = 	ip_addr;}
			else{
				cmd = *(buf + 25);
				if(cmd == 0x03){
					memcpy(&(*di_itr)->ip_, buf + 26, sizeof(unsigned long));
					__application_environment.virtual_ip_table_map_->insert(APPLICATION_ENVIRONMENT::IP_TABLE_PAIR((*di_itr)->ip_, *di_itr));
					//send respon
					CopyMemory(virtual_buf, buf, sizeof(virtual_buf));
					SecureZeroMemory(virtual_buf + 10, 4);
					CopyMemory(virtual_buf + 14, virtual_buf + 26, 4);
					ip.sin_family = AF_INET;
					ip.sin_port = htons(__application_environment.remote_port_);
					ip.sin_addr.s_addr = inet_addr(__application_environment.remote_ip_);
					udp_send((char*)virtual_buf, sizeof(virtual_buf), (SOCKADDR*)&ip);
				}
			}
		}

		_InterlockedIncrement(&__application_environment.pci_output_num_);
		return ret_code;
	}

	return ret_code;
}
// ´¦Àíº¯Êý
void CPcapRcvThread::OnProc(void)
{
	IP_Header* ih = NULL;
	UDP_Header* uh = NULL;
	unsigned int uiIPlength = 0;
	struct pcap_pkthdr* pkt_header = NULL;
	const u_char* pkt_data = NULL;
	unsigned short usDstPort = 0;
	bool bDownStream = false;
	CNetPcapComm::FrameDataStruct* pFrameData = NULL;
	while(1 == pcap_next_ex(m_pNetPcapComm->m_ptrPcap, &pkt_header, &pkt_data))
	{
		ih = (IP_Header *)(pkt_data + sizeof(Ethernet_Header));
		uiIPlength = (ih->ver_ihl & 0xf) * 4;
		uh = (UDP_Header *)((u_char*)ih + uiIPlength);
		if ((TRUE == m_pNetPcapComm->IfRcvPortExistInMap(uh->dport, &m_pNetPcapComm->m_oDownStreamRcvSndPortMap))
			&& (ih->saddr == m_pNetPcapComm->m_uiHighStreamIP))
		{
			bDownStream = true;
			usDstPort = m_pNetPcapComm->GetSndPortFromMap(uh->dport, &m_pNetPcapComm->m_oDownStreamRcvSndPortMap);
			_InterlockedIncrement(&m_pNetPcapComm->m_lDownStreamNetRevFrameNum);
		}
		else if ((TRUE == m_pNetPcapComm->IfRcvPortExistInMap(uh->dport, &m_pNetPcapComm->m_oUpStreamRcvSndPortMap))
			&& (ih->saddr == m_pNetPcapComm->m_uiLowStreamIP))
		{
			bDownStream = false;
			usDstPort = m_pNetPcapComm->GetSndPortFromMap(uh->dport, &m_pNetPcapComm->m_oUpStreamRcvSndPortMap);
			_InterlockedIncrement(&m_pNetPcapComm->m_lUpStreamNetRevFrameNum);
		}
		else
		{
			continue;
		}
		EnterCriticalSection(&m_pNetPcapComm->m_oSec);
		pFrameData = m_pNetPcapComm->GetFreeFrameData();
		pFrameData->m_bDownStream = bDownStream;
		pFrameData->m_usDstPort = usDstPort;
		pFrameData->m_uiLength = htons(uh->len) - sizeof(UDP_Header);
		memcpy(pFrameData->m_ucData, pkt_data + sizeof(Ethernet_Header) + sizeof(IP_Header)
			+ sizeof(UDP_Header), pFrameData->m_uiLength);
		if (bDownStream == true)
		{
			m_pNetPcapComm->m_olsFrameDataDownStream.push_back(pFrameData);
		}
		else
		{
			m_pNetPcapComm->m_olsFrameDataUpStream.push_back(pFrameData);
		}
		LeaveCriticalSection(&m_pNetPcapComm->m_oSec);
	}
}
Ejemplo n.º 4
0
NTSTATUS
NTAPI
IKsFilterFactory_fnQueryInterface(
    IKsFilterFactory * iface,
    IN  REFIID refiid,
    OUT PVOID* Output)
{
    NTSTATUS Status;

    IKsFilterFactoryImpl * This = (IKsFilterFactoryImpl*)CONTAINING_RECORD(iface, IKsFilterFactoryImpl, Header.OuterUnknown);

    if (IsEqualGUIDAligned(refiid, &IID_IUnknown))
    {
        *Output = &This->Header.OuterUnknown;
        _InterlockedIncrement(&This->ref);
        return STATUS_SUCCESS;
    }

    if (This->Header.ClientAggregate)
    {
         /* using client aggregate */
         Status = This->Header.ClientAggregate->lpVtbl->QueryInterface(This->Header.ClientAggregate, refiid, Output);

         if (NT_SUCCESS(Status))
         {
             /* client aggregate supports interface */
             return Status;
         }
    }

    DPRINT("IKsFilterFactory_fnQueryInterface no interface\n");
    return STATUS_NOT_SUPPORTED;
}
// Constructs a single PTD object, copying the given 'locale_data' if provided.
static void __cdecl construct_ptd(
    __acrt_ptd*         const ptd,
    __crt_locale_data** const locale_data
    ) throw()
{
    ptd->_rand_state  = 1;
    ptd->_pxcptacttab = const_cast<__crt_signal_action_t*>(__acrt_exception_action_table);

    // It is necessary to always have GLOBAL_LOCALE_BIT set in perthread data
    // because when doing bitwise or, we won't get __UPDATE_LOCALE to work when
    // global per thread locale is set.
    ptd->_own_locale = _GLOBAL_LOCALE_BIT;

    ptd->_multibyte_info = &__acrt_initial_multibyte_data;

    // Initialize _setloc_data. These are the only valuse that need to be
    // initialized.
    ptd->_setloc_data._cachein[0]  = L'C';
    ptd->_setloc_data._cacheout[0] = L'C';

    // Downlevel data is not initially used
    ptd->_setloc_downlevel_data = nullptr;

    __acrt_lock_and_call(__acrt_multibyte_cp_lock, [&]
    {
        _InterlockedIncrement(&ptd->_multibyte_info->refcount);
    });
    
    // We need to make sure that ptd->ptlocinfo in never nullptr, this saves us
    // perf counts when UPDATING locale.
    __acrt_lock_and_call(__acrt_locale_lock, [&]
    {
        replace_current_thread_locale_nolock(ptd, *locale_data);
    });
}
Ejemplo n.º 6
0
COIPIPELINE Engine::get_pipeline(void)
{
    Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
    if (thread == 0) {
        thread = new Thread(&m_proc_number);
        thread_setspecific(mic_thread_key, thread);
    }

    COIPIPELINE pipeline = thread->get_pipeline(m_index);
    if (pipeline == 0) {
        COIRESULT res;
        int proc_num;

#ifndef TARGET_WINNT
        proc_num = __sync_fetch_and_add(&m_proc_number, 1);
#else // TARGET_WINNT
        proc_num = _InterlockedIncrement(&m_proc_number);
#endif // TARGET_WINNT

        if (proc_num > COI_PIPELINE_MAX_PIPELINES) {
            LIBOFFLOAD_ERROR(c_coipipe_max_number, COI_PIPELINE_MAX_PIPELINES);
            LIBOFFLOAD_ABORT;
        }
        // create pipeline for this thread
        res = COI::PipelineCreate(m_process, 0, mic_stack_size, &pipeline);
        check_result(res, c_pipeline_create, m_index, res);
        thread->set_pipeline(m_index, pipeline);
    }
    return pipeline;
}
Ejemplo n.º 7
0
LONG
FASTCALL
VideoPortInterlockedIncrement(
    IN PLONG Addend)
{
    return _InterlockedIncrement(Addend);
}
Ejemplo n.º 8
0
NTSTATUS
NTAPI
IKsDevice_fnQueryInterface(
    IN IKsDevice * iface,
    REFIID refiid,
    PVOID* Output)
{
    NTSTATUS Status;
    PKSIDEVICE_HEADER This = (PKSIDEVICE_HEADER)CONTAINING_RECORD(iface, KSIDEVICE_HEADER, BasicHeader.OuterUnknown);

    if (IsEqualGUIDAligned(refiid, &IID_IUnknown))
    {
        *Output = &This->BasicHeader.OuterUnknown;
        _InterlockedIncrement(&This->ref);
        return STATUS_SUCCESS;
    }

    if (This->BasicHeader.ClientAggregate)
    {
        /* using client aggregate */
        Status = This->BasicHeader.ClientAggregate->lpVtbl->QueryInterface(This->BasicHeader.ClientAggregate, refiid, Output);

        if (NT_SUCCESS(Status))
        {
            /* client aggregate supports interface */
            return Status;
        }
    }

    DPRINT("IKsDevice_fnQueryInterface no interface\n");
    return STATUS_NOT_SUPPORTED;
}
Ejemplo n.º 9
0
/**
 * Queues a work item to a work queue.
 *
 * \param WorkQueue A work queue object.
 * \param Function A function to execute.
 * \param Context A user-defined value to pass to the function.
 * \param DeleteFunction A callback function that is executed when the work queue item is about to be freed.
 */
VOID PhQueueItemWorkQueueEx(
    _Inout_ PPH_WORK_QUEUE WorkQueue,
    _In_ PUSER_THREAD_START_ROUTINE Function,
    _In_opt_ PVOID Context,
    _In_opt_ PPH_WORK_QUEUE_ITEM_DELETE_FUNCTION DeleteFunction
    )
{
    PPH_WORK_QUEUE_ITEM workQueueItem;

    workQueueItem = PhpCreateWorkQueueItem(Function, Context, DeleteFunction);

    // Enqueue the work item.
    PhAcquireQueuedLockExclusive(&WorkQueue->QueueLock);
    InsertTailList(&WorkQueue->QueueListHead, &workQueueItem->ListEntry);
    _InterlockedIncrement(&WorkQueue->BusyCount);
    PhReleaseQueuedLockExclusive(&WorkQueue->QueueLock);
    // Signal the semaphore once to let a worker thread continue.
    NtReleaseSemaphore(PhpGetSemaphoreWorkQueue(WorkQueue), 1, NULL);

    PHLIB_INC_STATISTIC(WqWorkItemsQueued);

    // Check if all worker threads are currently busy, and if we can create more threads.
    if (WorkQueue->BusyCount >= WorkQueue->CurrentThreads &&
        WorkQueue->CurrentThreads < WorkQueue->MaximumThreads)
    {
        // Lock and re-check.
        PhAcquireQueuedLockExclusive(&WorkQueue->StateLock);

        if (WorkQueue->CurrentThreads < WorkQueue->MaximumThreads)
            PhpCreateWorkQueueThread(WorkQueue);

        PhReleaseQueuedLockExclusive(&WorkQueue->StateLock);
    }
}
Ejemplo n.º 10
0
LONG
WINAPI
redirect_InterlockedIncrement(
    __inout __drv_interlocked LONG volatile *Addend
    )
{
    return _InterlockedIncrement(Addend);
}
Ejemplo n.º 11
0
NTKERNELAPI
LONG
FASTCALL
InterlockedIncrement
(IN OUT LONG volatile *Addend)
{
    return _InterlockedIncrement(Addend);
}
Ejemplo n.º 12
0
long atomic_increment(volatile long* value)
{
#ifdef __GNUC__
	return __sync_add_and_fetch(value, 1);	
#else
	return _InterlockedIncrement(value);
#endif
}
Ejemplo n.º 13
0
/**
  Performs an atomic increment of an 32-bit unsigned integer.

  Performs an atomic increment of the 32-bit unsigned integer specified by
  Value and returns the incremented value. The increment operation must be
  performed using MP safe mechanisms. The state of the return value is not
  guaranteed to be MP safe.

  @param  Value A pointer to the 32-bit value to increment.

  @return The incremented value.

**/
UINT32
EFIAPI
InternalSyncIncrement (
  IN      UINT32                    *Value
  )
{
  return _InterlockedIncrement (Value);
}
Ejemplo n.º 14
0
UINT32
EFIAPI
InternalSyncIncrement (
  IN      volatile UINT32           *Value
  )
{
  return _InterlockedIncrement ((long *)Value);
}
Ejemplo n.º 15
0
void MConHandle::LogHandle(UINT evt, HANDLE h)
{
	LONG i = (_InterlockedIncrement(&m_logidx) & (HANDLE_BUFFER_SIZE - 1));
	m_log[i].evt = (Event::EventType)evt;
	DEBUGTEST(m_log[i].time = GetTickCount());
	m_log[i].TID = GetCurrentThreadId();
	m_log[i].h = h;
}
Ejemplo n.º 16
0
NTSTATUS PhpThreadQueryWorker(
    __in PVOID Parameter
    )
{
    PPH_THREAD_QUERY_DATA data = (PPH_THREAD_QUERY_DATA)Parameter;
    LONG newSymbolsLoading;

    newSymbolsLoading = _InterlockedIncrement(&data->ThreadProvider->SymbolsLoading);

    if (newSymbolsLoading == 1)
        PhInvokeCallback(&data->ThreadProvider->LoadingStateChangedEvent, (PVOID)TRUE);

    // We can't resolve the start address until symbols have
    // been loaded.
    PhWaitForEvent(&data->ThreadProvider->SymbolsLoadedEvent, NULL);

    data->StartAddressString = PhGetSymbolFromAddress(
        data->ThreadProvider->SymbolProvider,
        data->ThreadItem->StartAddress,
        &data->StartAddressResolveLevel,
        &data->ThreadItem->StartAddressFileName,
        NULL,
        NULL
        );

    newSymbolsLoading = _InterlockedDecrement(&data->ThreadProvider->SymbolsLoading);

    if (newSymbolsLoading == 0)
        PhInvokeCallback(&data->ThreadProvider->LoadingStateChangedEvent, (PVOID)FALSE);

    // Get the service tag, and the service name.
    if (
        WINDOWS_HAS_SERVICE_TAGS &&
        data->ThreadProvider->SymbolProvider->IsRealHandle &&
        data->ThreadItem->ThreadHandle
        )
    {
        PVOID serviceTag;

        if (NT_SUCCESS(PhGetThreadServiceTag(
            data->ThreadItem->ThreadHandle,
            data->ThreadProvider->ProcessHandle,
            &serviceTag
            )))
        {
            data->ServiceName = PhGetServiceNameFromTag(
                data->ThreadProvider->ProcessId,
                serviceTag
                );
        }
    }

    RtlInterlockedPushEntrySList(&data->ThreadProvider->QueryListHead, &data->ListEntry);

    PhDereferenceObject(data->ThreadProvider);

    return STATUS_SUCCESS;
}
Ejemplo n.º 17
0
    void
    shared_count::add_shared()
    {
#ifdef _MSC_VER
        _InterlockedIncrement(&shared_owners_);
#else
        ++shared_owners_;
#endif
    }
Ejemplo n.º 18
0
/**
 * References the specified object.
 *
 * \param Object A pointer to the object to reference.
 */
VOID PhReferenceObject(
    __in PVOID Object
    )
{
    PPH_OBJECT_HEADER objectHeader;

    objectHeader = PhObjectToObjectHeader(Object);
    /* Increment the reference count. */
    _InterlockedIncrement(&objectHeader->RefCount);
}
Ejemplo n.º 19
0
DWORD WINAPI apiThreadHelper(LPVOID lpParameter)
{
	ConEmuThreadStartArg* p = (ConEmuThreadStartArg*)lpParameter;

	#if defined(_MSC_VER) && !defined(CONEMU_MINIMAL)
	if (IsDebuggerPresent())
	{
		SetThreadName((DWORD)-1, p->sName);
	}
	#endif

	ConEmuThreadInfo Info = {
		GetCurrentThreadId(),
		TRUE,
		p,
		p->hThread,
		p->lpStartAddress,
		p->nParentTID,
		GetTickCount()
	};
	lstrcpynA(Info.sName, p->sName, countof(Info.sName));

	ConEmuThreadInfo* pInfo = NULL;
	for (INT_PTR c = THREADS_LOG_SIZE; --c >= 0;)
	{
		LONG i = (_InterlockedIncrement(&g_ThreadsIdx) & (THREADS_LOG_SIZE-1));
		if (!g_Threads[i].bActive)
		{
			g_Threads[i] = Info;
			pInfo = (g_Threads+i);
			break;
		}
	}
	if (!pInfo)
	{
		_ASSERTE(pInfo!=NULL && "Too many active threads?");
	}


	// Run the thread routine
	DWORD nRc = p->lpStartAddress(p->lpParameter);


	// Thread is finishing
	if (pInfo && pInfo->bActive && (pInfo->nThreadID == Info.nThreadID))
	{
		pInfo->nExitCode = nRc;
		pInfo->nEndTick = GetTickCount();
		pInfo->bActive = FALSE;
	}

	// Done
	delete p;
	return nRc;
}
Ejemplo n.º 20
0
VOID PhSvcHandleConnectionRequest(
    __in PPHSVC_API_MSG Message
    )
{
    NTSTATUS status;
    PPHSVC_CLIENT client;
    HANDLE portHandle;
    REMOTE_PORT_VIEW clientView;

    client = PhSvcCreateClient(&Message->h.ClientId);

    if (!client)
    {
        NtAcceptConnectPort(&portHandle, NULL, &Message->h, FALSE, NULL, NULL);
        return;
    }

    Message->ConnectInfo.ServerProcessId = NtCurrentProcessId();

    clientView.Length = sizeof(REMOTE_PORT_VIEW);
    clientView.ViewSize = 0;
    clientView.ViewBase = NULL;

    status = NtAcceptConnectPort(
        &portHandle,
        client,
        &Message->h,
        TRUE,
        NULL,
        &clientView
        );

    if (!NT_SUCCESS(status))
    {
        PhDereferenceObject(client);
        return;
    }

    client->PortHandle = portHandle;
    client->ClientViewBase = clientView.ViewBase;
    client->ClientViewLimit = (PCHAR)clientView.ViewBase + clientView.ViewSize;

    status = NtCompleteConnectPort(portHandle);

    if (!NT_SUCCESS(status))
    {
        PhDereferenceObject(client);
        return;
    }

    if (_InterlockedIncrement(&PhSvcApiNumberOfClients) == 1)
    {
        NtSetEvent(PhSvcTimeoutCancelEventHandle, NULL);
    }
}
Ejemplo n.º 21
0
void UCTParallel::search_uct_root(Board& board, const Color color, UCTNode* node, UCTNode* copychild)
{
	// UCBからプレイアウトする手を選択
	// rootノードはアトミックに更新するためUCB計算ではロックしない
	UCTNode* selected_node = select_node_with_ucb(node);

	// rootでは全て合法手なのでエラーチェックはしない
	board.move_legal(selected_node->xy, color);

	// コピーされたノードに変換
	UCTNode* selected_node_copy = copychild + (selected_node - node->child);

	int win;

	// 閾値以下の場合プレイアウト(全スレッドの合計値)
	if (selected_node->playout_num < THR)
	{
		win = 1 - playout(board, opponent(color));
	}
	else {
		if (selected_node_copy->child_num == 0)
		{
			// ノードを展開
			if (selected_node_copy->expand_node(board))
			{
				win = 1 - search_uct(board, opponent(color), selected_node_copy);
			}
			else {
				// ノードプール不足
				win = 1 - playout(board, opponent(color));
			}
		}
		else {
			win = 1 - search_uct(board, opponent(color), selected_node_copy);
		}
	}

	// 勝率を更新(アトミックに加算)
	_InterlockedExchangeAdd(&selected_node->win_num, win);
	_InterlockedIncrement(&selected_node->playout_num);
	_InterlockedIncrement(&node->playout_num_sum);
}
Ejemplo n.º 22
0
int atomic_increment(volatile int *value)
{
    assert(value);
    assert((int)value % 4 == 0); // Only 32 bit aligned values work.
#if LOOM_COMPILER == LOOM_COMPILER_MSVC
    return _InterlockedIncrement(value);

#else
    return __sync_sub_and_fetch(value, 1);
#endif
}
Ejemplo n.º 23
0
INTERLOCKED_RESULT
FASTCALL
Exfi386InterlockedIncrementLong(
    IN OUT LONG volatile *Addend)
{
    LONG Result;

    Result = _InterlockedIncrement(Addend);
    return (Result < 0) ? ResultNegative :
           (Result > 0) ? ResultPositive :
           ResultZero;
}
Ejemplo n.º 24
0
INTERLOCKED_RESULT
NTAPI
Exi386InterlockedIncrementLong(
    IN PLONG Addend)
{
    LONG Result;

    Result = _InterlockedIncrement(Addend);
    return (Result < 0) ? ResultNegative :
           (Result > 0) ? ResultPositive :
           ResultZero;
}
static LFDS611_INLINE                   lfds611_atom_t
lfds611_abstraction_increment (
  volatile lfds611_atom_t * value)
{
  lfds611_atom_t                          rv;

  assert (value != NULL);
  LFDS611_BARRIER_COMPILER_FULL;
  rv = (lfds611_atom_t) _InterlockedIncrement ((long int *)value);
  LFDS611_BARRIER_COMPILER_FULL;
  return (rv);
}
Ejemplo n.º 26
0
Threading::MutexRecursive::MutexRecursive() : Mutex( false )
{
	if( _InterlockedIncrement( &_attr_refcount ) == 1 )
	{
		if( 0 != pthread_mutexattr_init( &_attr_recursive ) )
			throw Exception::OutOfMemory(L"Recursive mutexing attributes");

		pthread_mutexattr_settype( &_attr_recursive, PTHREAD_MUTEX_RECURSIVE );
	}

	if (pthread_mutex_init( &m_mutex, &_attr_recursive ))
		Console.Error( "(Thread Log) Failed to initialize mutex.");
}
	handle *frontend_controller::profile(const void *in_image_address)
	{
		if (1 == _InterlockedIncrement(_worker_refcount.get()))
		{
			shared_ptr<void> exit_event(::CreateEvent(NULL, TRUE, FALSE, NULL), &::CloseHandle);
			auto_ptr<thread> frontend_thread(new thread(bind(&frontend_controller::frontend_worker,
				_frontend_thread.get(), _factory, &_collector, _image_load_queue, exit_event)));

			_frontend_thread.release();

			swap(_exit_event, exit_event);
			swap(_frontend_thread, frontend_thread);
		}

		return new profiler_instance(in_image_address, _image_load_queue, _worker_refcount, _exit_event);
	}
unsigned __stdcall input_thread_proc(void* args)
{

	//	WaitForSingleObject(ppi_ptr->parallel_stop_event_, ppi_ptr->waiting_time_);
	PARALLEL_PORT_IMPL_PTR ppi_ptr = (PARALLEL_PORT_IMPL_PTR)args;
	DWORD result = 0x0;
	PARALLEL_OUTPUT_QUEUE_ITEM item;
	LARGE_INTEGER  litmp; 
	LONGLONG       QPart1,QPart2;;
	double         minute, freq, tim; 
	int i = 0;

	while(ppi_ptr->is_running_){

		QueryPerformanceFrequency(&litmp); 
		freq = (double)litmp.QuadPart; 
		QueryPerformanceCounter(&litmp); 
		QPart1 = litmp.QuadPart; 

		do{
			result = WaitForSingleObject(ppi_ptr->parallel_stop_event_, 0);
			if(result == WAIT_OBJECT_0)	goto END;

			QueryPerformanceCounter(&litmp); 
			QPart2 = litmp.QuadPart;
			minute = (double)(QPart2-QPart1); 
			tim = minute / freq; 
		}while(tim<0.01);

		for(i = 0; i < 4; ++i){
			if(parallel_output_queue_pop(&item)){
				if(output_data_into_parallel_port(item.buf_, sizeof(item.buf_)) != -1){
					_InterlockedIncrement(&__simple_proc_env.application_environment_->pci_output_num_);
				}
				else{
					OUTPUT_DEBUG_STRING("Write a pallerl error!");
				}
			}
		}

	}
END:

	_endthreadex(0);
	return 0;
}
Ejemplo n.º 29
0
NTSTATUS
NTAPI
IKsAllocator_fnQueryInterface(
    IKsAllocator * iface,
    IN  REFIID refiid,
    OUT PVOID* Output)
{
    PALLOCATOR This = (PALLOCATOR)CONTAINING_RECORD(iface, ALLOCATOR, lpVtbl);

    if (IsEqualGUIDAligned(refiid, &IID_IUnknown) ||
        IsEqualGUIDAligned(refiid, &IID_IKsAllocator))
    {
        *Output = &This->lpVtbl;
        _InterlockedIncrement(&This->ref);
        return STATUS_SUCCESS;
    }
    return STATUS_UNSUCCESSFUL;
}
Ejemplo n.º 30
0
  // Main loop for the worker threads
VOID TaskScheduler::ExecuteTasks()
{
      // Get the ID for the thread
    const UINT iContextId = _InterlockedIncrement((LONG*)&muContextId);
      // Start reading from the beginning of the work queue
    INT  iReader = 0;

      // Thread keeps recieving and executing tasks until it is terminated
    while(mbAlive == TRUE)
    {
          // Get a Handle from the work queue
        TASKSETHANDLE handle = mhActiveTaskSets[iReader];

          // If there is a TaskSet in the slot execute a task
        if(handle != TASKSETHANDLE_INVALID)
        {
            TaskMgrSS::TaskSet *pSet = &gTaskMgrSS.mSets[handle];
            if(pSet->muCompletionCount > 0 && pSet->muTaskId >= 0)
            {
                pSet->Execute(iContextId);
            }
            else
            {
                _InterlockedCompareExchange((LONG*)&mhActiveTaskSets[iReader],TASKSETHANDLE_INVALID,handle);
                iReader = (iReader + 1) & (MAX_TASKSETS - 1);
            }
        }
          // Otherwise keep looking for work
        else if(miTaskCount > 0)
        {
            iReader = (iReader + 1) & (MAX_TASKSETS - 1);
        }
          // or sleep if all of the work has been completed
        else
        {
            if(miTaskCount <= 0)
            {
                WaitForSingleObject(mhTaskAvailable,INFINITE);
            }
        }
    }
}