本文整理汇总了C++中TerminateThread函数的典型用法代码示例。如果您正苦于以下问题:C++ TerminateThread函数的具体用法?C++ TerminateThread怎么用?C++ TerminateThread使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了TerminateThread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: doexec
BOOL
doexec(
SOCKET ClientSocket
)
{
PSESSION_DATA Session = CreateSession();
SECURITY_ATTRIBUTES SecurityAttributes;
DWORD ThreadId;
HANDLE HandleArray[3];
int i;
SecurityAttributes.nLength = sizeof(SecurityAttributes);
SecurityAttributes.lpSecurityDescriptor = NULL; // Use default ACL
SecurityAttributes.bInheritHandle = FALSE; // No inheritance
//
// Store the client socket handle in the session structure so the thread
// can get at it. This also signals that the session is connected.
//
Session->ClientSocket = ClientSocket;
//
// Create the session threads
//
Session->ReadShellThreadHandle =
CreateThread(&SecurityAttributes, 0,
(LPTHREAD_START_ROUTINE) SessionReadShellThreadFn,
(LPVOID) Session, 0, &ThreadId);
if (Session->ReadShellThreadHandle == NULL) {
holler("Failed to create ReadShell session thread, error = %s",
itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);
//
// Reset the client pipe handle to indicate this session is disconnected
//
Session->ClientSocket = INVALID_SOCKET;
return(FALSE);
}
Session->WriteShellThreadHandle =
CreateThread(&SecurityAttributes, 0,
(LPTHREAD_START_ROUTINE) SessionWriteShellThreadFn,
(LPVOID) Session, 0, &ThreadId);
if (Session->WriteShellThreadHandle == NULL) {
holler("Failed to create ReadShell session thread, error = %s",
itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);
//
// Reset the client pipe handle to indicate this session is disconnected
//
Session->ClientSocket = INVALID_SOCKET;
TerminateThread(Session->WriteShellThreadHandle, 0);
return(FALSE);
}
//
// Wait for either thread or the shell process to finish
//
HandleArray[0] = Session->ReadShellThreadHandle;
HandleArray[1] = Session->WriteShellThreadHandle;
HandleArray[2] = Session->ProcessHandle;
i = WaitForMultipleObjects(3, HandleArray, FALSE, 0xffffffff);
switch (i) {
case WAIT_OBJECT_0 + 0:
TerminateThread(Session->WriteShellThreadHandle, 0);
TerminateProcess(Session->ProcessHandle, 1);
break;
case WAIT_OBJECT_0 + 1:
TerminateThread(Session->ReadShellThreadHandle, 0);
TerminateProcess(Session->ProcessHandle, 1);
break;
case WAIT_OBJECT_0 + 2:
TerminateThread(Session->WriteShellThreadHandle, 0);
TerminateThread(Session->ReadShellThreadHandle, 0);
break;
default:
holler("WaitForMultipleObjects error: %s",
itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);
break;
}
// Close my handles to the threads, the shell process, and the shell pipes
shutdown(Session->ClientSocket, SD_BOTH);
closesocket(Session->ClientSocket);
DisconnectNamedPipe(Session->ReadPipeHandle);
CloseHandle(Session->ReadPipeHandle);
//.........这里部分代码省略.........
示例2: RevokeDragDrop
CDragDrop::~CDragDrop()
{
//DestroyDragImageBits();
//DestroyDragImageWindow();
if (mb_DragDropRegistered && ghWnd)
{
mb_DragDropRegistered = FALSE;
RevokeDragDrop(ghWnd);
}
MSectionLockSimple CS;
CS.Lock(mp_CrThreads);
BOOL lbEmpty = m_OpThread.empty() && !InDragDrop();
CS.Unlock();
if (!lbEmpty)
{
if (MessageBox(ghWnd, L"Not all shell operations was finished!\r\nDo You want to terminate them (it's may be harmful)?",
gpConEmu->GetDefaultTitle(), MB_YESNO|MB_ICONEXCLAMATION) == IDYES)
{
// Terminate all shell (copying) threads
CS.Lock(mp_CrThreads);
//std::vector<ThInfo>::iterator iter = m_OpThread.begin();
//while (iter != m_OpThread.end())
while (m_OpThread.size() > 0)
{
INT_PTR j = m_OpThread.size()-1;
const ThInfo* iter = &(m_OpThread[j]);
HANDLE hThread = iter->hThread;
TerminateThread(hThread, 100);
CloseHandle(hThread);
//iter = m_OpThread.erase(iter);
m_OpThread.erase(j);
}
CS.Unlock();
}
else
{
// Wait until finished
BOOL lbActive = TRUE;
while (lbActive)
{
Sleep(100);
CS.Lock(mp_CrThreads);
lbActive = (!m_OpThread.empty()) || InDragDrop();
CS.Unlock();
}
}
}
else
{
// незаконченных нитей нет
// -- Leave Critical Section(&m_CrThreads); -- 101229 секция уже закрыта
}
// Завершение всех нитей драга
TerminateDrag();
//if (m_pfpi) free(m_pfpi); m_pfpi=NULL;
//if (mp_DesktopID) { CoTaskMemFree(mp_DesktopID); mp_DesktopID = NULL; }
SafeDelete(mp_CrThreads);
}
示例3: stubSPUSafeTearDown
static void stubSPUSafeTearDown(void)
{
#ifdef CHROMIUM_THREADSAFE
CRmutex *mutex;
#endif
if (!stub_initialized) return;
stub_initialized = 0;
#ifdef CHROMIUM_THREADSAFE
mutex = &stub.mutex;
crLockMutex(mutex);
#endif
crDebug("stubSPUSafeTearDown");
#ifdef WINDOWS
# ifndef CR_NEWWINTRACK
stubUninstallWindowMessageHook();
# endif
#endif
#if defined(CR_NEWWINTRACK)
crUnlockMutex(mutex);
# if defined(WINDOWS)
if (RTThreadGetState(stub.hSyncThread)!=RTTHREADSTATE_TERMINATED)
{
HANDLE hNative;
DWORD ec=0;
hNative = OpenThread(SYNCHRONIZE|THREAD_QUERY_INFORMATION|THREAD_TERMINATE,
false, RTThreadGetNative(stub.hSyncThread));
if (!hNative)
{
crWarning("Failed to get handle for sync thread(%#x)", GetLastError());
}
else
{
crDebug("Got handle %p for thread %#x", hNative, RTThreadGetNative(stub.hSyncThread));
}
ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
if (PostThreadMessage(RTThreadGetNative(stub.hSyncThread), WM_QUIT, 0, 0))
{
RTThreadWait(stub.hSyncThread, 1000, NULL);
/*Same issue as on linux, RTThreadWait exits before system thread is terminated, which leads
* to issues as our dll goes to be unloaded.
*@todo
*We usually call this function from DllMain which seems to be holding some lock and thus we have to
* kill thread via TerminateThread.
*/
if (WaitForSingleObject(hNative, 100)==WAIT_TIMEOUT)
{
crDebug("Wait failed, terminating");
if (!TerminateThread(hNative, 1))
{
crDebug("TerminateThread failed");
}
}
if (GetExitCodeThread(hNative, &ec))
{
crDebug("Thread %p exited with ec=%i", hNative, ec);
}
else
{
crDebug("GetExitCodeThread failed(%#x)", GetLastError());
}
}
else
{
crDebug("Sync thread killed before DLL_PROCESS_DETACH");
}
if (hNative)
{
CloseHandle(hNative);
}
}
#else
if (stub.hSyncThread!=NIL_RTTHREAD)
{
ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
{
/*RTThreadWait might return too early, which cause our code being unloaded while RT thread wrapper is still running*/
int rc = pthread_join(RTThreadGetNative(stub.hSyncThread), NULL);
if (!rc)
{
crDebug("pthread_join failed %i", rc);
}
}
}
#endif
crLockMutex(mutex);
#endif
#ifndef WINDOWS
crNetTearDown();
#endif
//.........这里部分代码省略.........
示例4: _tmain
//.........这里部分代码省略.........
// by CreateFile cannot be inherited by any child processes the application
__in DWORD dwCreationDisposition,
__in DWORD dwFlagsAndAttributes,
// The file or device attributes and flags,
// FILE_ATTRIBUTE_NORMAL being the most common default value for files.
__in_opt HANDLE hTemplateFile
);
*/
HANDLE hThread[2];
hThread[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartFileMonitor, NULL, 0, NULL);
hThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartRegistryMonitor, NULL, 0, NULL);
/*
*** CreateThread
Creates a thread to execute within the virtual address space of the calling process.
To create a thread that runs in the virtual address space of another process,
use the CreateRemoteThread function.
WINBASEAPI
__out_opt
HANDLE
WINAPI
CreateThread(
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
// A pointer to a SECURITY_ATTRIBUTES structure that determines
// whether the returned handle can be inherited by child processes.
// NULL : the handle cannot be inherited.
__in SIZE_T dwStackSize,
// The initial size of the stack, in bytes.
// 0 : the new thread uses the default size for the executable.
__in LPTHREAD_START_ROUTINE lpStartAddress,
__in_opt __deref __drv_aliasesMem LPVOID lpParameter,
// A pointer to a variable to be passed to the thread.
__in DWORD dwCreationFlags,
// The flags that control the creation of the thread.
// 0 : The thread runs immediately after creation.
__out_opt LPDWORD lpThreadId
// A pointer to a variable that receives the thread identifier.
// NULL : the thread identifier is not returned.
);
*/
WaitForMultipleObjects(2, (const HANDLE*)&hThread, TRUE, INFINITE); // WinBash.h
/*
*** WaitForMultipleObjects
Waits until one or all of the specified objects are
in the signaled state or the time-out interval elapses.
WINBASEAPI
DWORD
WINAPI
WaitForMultipleObjects(
__in DWORD nCount,
__in_ecount(nCount) CONST HANDLE *lpHandles,
__in BOOL bWaitAll,
// TRUE : the function returns when the state of all objects
// in the lpHandles array is signaled.
__in DWORD dwMilliseconds
// The time-out interval, in milliseconds.
// INFINITE : the function will return only when the specified objects are signaled.
);
*/
TerminateThread(g_hRegWatch[0], 0);
TerminateThread(g_hRegWatch[1], 0);
/*
*** TerminateThread
WINBASEAPI
BOOL
WINAPI
TerminateThread(
__in HANDLE hThread,
__in DWORD dwExitCode
);
TerminatedThread를 사용하면 스레드가 제대로 정리되지 않는다.
대부분 최후의 경우에만 사용해야 하는 위험한 함수다.
적절하게 종료하기 위한 방법 :
1. CreateEvent 함수를 사용하여 이벤트 개체를 만든다.
2. 스레드를 만든다.
3. 각 스레드는 WaitForSingleObject 함수를 호출하여 이벤트 상태를 모니터링한다.
4. 각 스레드는 이벤트가 신호를 받는 상태 (WaitForSingleObjtect)가 WAIT_OBJECT_0을 반환)로 설정되었을 때 실행을 종료한다.
*/
CloseHandle(g_hStopEvent);
CloseHandle(g_hFile);
/*
WINBASEAPI
BOOL
WINAPI
CloseHandle( __in HANDLE hObject );
*/
_tprintf(_T("Program terminating.\n"));
}
示例5: TerminateThread
void ThreadImpl::terminate()
{
if (m_thread)
TerminateThread(m_thread, 0);
}
示例6: TerminateThread
WinThread::~WinThread()
{
TerminateThread(this->_th, 0);
CloseHandle(this->_th);
delete this->_call;
}
示例7: main
int main(int argc, char *argv[])
{
CNV11* NV11 = new CNV11(); // Create instance of validator class
// Start the polling thread, this will not send any polls until
// the IsPolling variable is true
HANDLE nv11Thread = StartPollThread(NV11);
// Set output to std::cout
NV11->SetOutputStream(&cout);
WriteString("Example C++ NV11 SDK\n\nSearching for ports...\n");
// Find out about the validator and create a connection struct to pass
// to the validator class
SSP_COMMAND commandStructure;
commandStructure.BaudRate = 9600;
commandStructure.Timeout = 1000;
commandStructure.RetryLevel = 3;
commandStructure.IgnoreError = 1;
char* end;
// Get port number
std::vector<string> ports = GetComPorts();
for (unsigned int i = 0; i < ports.size(); ++i)
cout << ports[i] << endl;
string in = "";
unsigned int portIndex = 0;
do
{
in = GetInputString("Select a port: ");
portIndex = strtol(in.c_str(), &end, 0);
} while (portIndex <= 0 || portIndex > ports.size());
commandStructure.PortNumber = FormatComPort(ports[portIndex-1]);
// Get ssp address
int ssp = 0;
do
{
in = GetInputString("SSP Address (Default = 0): ");
ssp = strtol(in.c_str(), &end, 0);
} while (ssp < 0 || ssp > 32 || end == in.c_str());
commandStructure.SSPAddress = (unsigned char)ssp;
// Get protocol version to use
int p = 0;
do
{
in = GetInputString("Protocol version: ");
p = strtol(in.c_str(), &end, 0);
} while (p <= 0 || p > MAX_PROTOCOL_VERSION);
// Now connect to validator
if (NV11->ConnectToValidator(commandStructure, p, 5))
{
WriteString("Connected to validator successfully");
DisplayCommands();
while (true)
{
// Parse the keys, if this returns false then the user has selected
// to exit the program
if (!ParseKeys(NV11))
{
IsPolling = false; // Stop polling before exit
break;
}
// If PollFailed is set by the polling thread, attempt to reconnect to the unit
if (PollFailed)
{
// Make 5 attempts to reconnect, if none successful break out
if (NV11->ConnectToValidator(commandStructure, p, 5))
{
// If successful reconnect, restart the polling thread and continue
PollFailed = false;
TerminateThread(nv11Thread, 0);
CloseHandle(nv11Thread);
nv11Thread = StartPollThread(NV11);
}
else
break;
}
}
WriteString("Poll loop stopped");
}
TerminateThread(nv11Thread, 0);
CloseHandle(nv11Thread);
delete NV11;
WriteString("Press any key to exit...");
_getch();
}
示例8: lock
VOID
IN_PROCESS_APPLICATION::ShutDownInternal()
{
DWORD dwThreadStatus = 0;
DWORD dwTimeout = m_pConfig->QueryShutdownTimeLimitInMS();
HANDLE handle = NULL;
WIN32_FIND_DATA fileData;
if (IsDebuggerPresent())
{
dwTimeout = INFINITE;
}
if (m_fShutdownCalledFromNative ||
m_status == APPLICATION_STATUS::STARTING ||
m_status == APPLICATION_STATUS::FAIL)
{
return;
}
{
SRWLockWrapper lock(m_srwLock);
if (m_fShutdownCalledFromNative ||
m_status == APPLICATION_STATUS::STARTING ||
m_status == APPLICATION_STATUS::FAIL)
{
return;
}
// We need to keep track of when both managed and native initiate shutdown
// to avoid AVs. If shutdown has already been initiated in managed, we don't want to call into
// managed. We still need to wait on main exiting no matter what. m_fShutdownCalledFromNative
// is used for detecting redundant calls and blocking more requests to OnExecuteRequestHandler.
m_fShutdownCalledFromNative = TRUE;
m_status = APPLICATION_STATUS::SHUTDOWN;
if (!m_fShutdownCalledFromManaged)
{
// We cannot call into managed if the dll is detaching from the process.
// Calling into managed code when the dll is detaching is strictly a bad idea,
// and usually results in an AV saying "The string binding is invalid"
if (!g_fProcessDetach)
{
m_ShutdownHandler(m_ShutdownHandlerContext);
m_ShutdownHandler = NULL;
}
}
// Release the lock before we wait on the thread to exit.
}
if (!m_fShutdownCalledFromManaged)
{
if (m_hThread != NULL &&
GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 &&
dwThreadStatus == STILL_ACTIVE)
{
// wait for graceful shutdown, i.e., the exit of the background thread or timeout
if (WaitForSingleObject(m_hThread, dwTimeout) != WAIT_OBJECT_0)
{
// if the thread is still running, we need kill it first before exit to avoid AV
if (GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 && dwThreadStatus == STILL_ACTIVE)
{
// Calling back into managed at this point is prone to have AVs
// Calling terminate thread here may be our best solution.
TerminateThread(m_hThread, STATUS_CONTROL_C_EXIT);
}
}
}
}
CloseHandle(m_hThread);
m_hThread = NULL;
s_Application = NULL;
CloseStdErrHandles();
if (m_pStdFile != NULL)
{
fflush(stdout);
fflush(stderr);
fclose(m_pStdFile);
}
if (m_hLogFileHandle != INVALID_HANDLE_VALUE)
{
m_Timer.CancelTimer();
CloseHandle(m_hLogFileHandle);
m_hLogFileHandle = INVALID_HANDLE_VALUE;
}
// delete empty log file
handle = FindFirstFile(m_struLogFilePath.QueryStr(), &fileData);
if (handle != INVALID_HANDLE_VALUE &&
fileData.nFileSizeHigh == 0 &&
fileData.nFileSizeLow == 0) // skip check of nFileSizeHigh
{
FindClose(handle);
// no need to check whether the deletion succeeds
//.........这里部分代码省略.........
示例9: ReferenceApplication
// Will be called by the inprocesshandler
HRESULT
IN_PROCESS_APPLICATION::LoadManagedApplication
(
VOID
)
{
HRESULT hr = S_OK;
DWORD dwTimeout;
DWORD dwResult;
ReferenceApplication();
if (m_status != APPLICATION_STATUS::STARTING)
{
// Core CLR has already been loaded.
// Cannot load more than once even there was a failure
if (m_status == APPLICATION_STATUS::FAIL)
{
hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
}
else if (m_status == APPLICATION_STATUS::SHUTDOWN)
{
hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED);
}
goto Finished;
}
// Set up stdout redirect
SetStdOut();
{
SRWLockWrapper lock(m_srwLock);
if (m_status != APPLICATION_STATUS::STARTING)
{
if (m_status == APPLICATION_STATUS::FAIL)
{
hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
}
else if (m_status == APPLICATION_STATUS::SHUTDOWN)
{
hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED);
}
goto Finished;
}
m_hThread = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE)ExecuteAspNetCoreProcess,
this, // thread function arguments
0, // default creation flags
NULL); // receive thread identifier
if (m_hThread == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Finished;
}
m_pInitalizeEvent = CreateEvent(
NULL, // default security attributes
TRUE, // manual reset event
FALSE, // not set
NULL); // name
if (m_pInitalizeEvent == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
// If the debugger is attached, never timeout
if (IsDebuggerPresent())
{
dwTimeout = INFINITE;
}
else
{
dwTimeout = m_pConfig->QueryStartupTimeLimitInMS();
}
const HANDLE pHandles[2]{ m_hThread, m_pInitalizeEvent };
// Wait on either the thread to complete or the event to be set
dwResult = WaitForMultipleObjects(2, pHandles, FALSE, dwTimeout);
// It all timed out
if (dwResult == WAIT_TIMEOUT)
{
// kill the backend thread as loading dotnet timedout
TerminateThread(m_hThread, 0);
hr = HRESULT_FROM_WIN32(dwResult);
goto Finished;
}
else if (dwResult == WAIT_FAILED)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Finished;
}
//.........这里部分代码省略.........
示例10: TerminateThread
CReg_ControlDlg::~CReg_ControlDlg()
{
if(hFirstThread!=NULL)
TerminateThread(hFirstThread, 0);
}
示例11: mainproc
int mainproc() {
memset(&pi, 0, sizeof(pi));
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
#ifndef REDIRECTIO
//Windows does this automatically but since we have a separate app and all, let's make sure.
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
#else
HANDLE hWriteStdIn, hReadStdOut, hReadStdErr;
makeOutputPipe(&hWriteStdIn, &si.hStdInput);
makeInputPipe(&si.hStdOutput, &hReadStdOut);
makeInputPipe(&si.hStdError, &hReadStdErr);
#endif
TCHAR* moduleFilename = GetModuleFilenameStr(0);
TCHAR* appName = replaceFilename(moduleFilename, L"Grabber.exe");
TCHAR* cmdLine = buildCommandLine(GetCommandLine(), L" -c");
if (!CreateProcess(appName, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
ThrowLastOsError(L"Cannot run the core application.");
CloseHandle(pi.hThread);
delete cmdLine;
delete appName;
delete moduleFilename;
#ifndef REDIRECTIO
DWORD res = WaitForSingleObject(pi.hProcess, INFINITE);
#else
//These went to children process
CloseHandle(si.hStdInput);
CloseHandle(si.hStdError);
CloseHandle(si.hStdOutput);
HANDLE hInputThread = RunTranslationThread(GetStdHandle(STD_INPUT_HANDLE), hWriteStdIn);
#ifdef THREADEDOUTPUT
HANDLE hOutputThread = RunTranslationThread(hReadStdOut, GetStdHandle(STD_OUTPUT_HANDLE));
HANDLE hErrorThread = RunTranslationThread(hReadStdErr, GetStdHandle(STD_ERROR_HANDLE));
#else
HANDLE hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hStdError = GetStdHandle(STD_ERROR_HANDLE);
#endif
DWORD res = 0;
do {
#ifndef THREADEDOUTPUT
TryTranslateOutput(hReadStdOut, hStdOutput);
TryTranslateOutput(hReadStdErr, hStdError);
#endif
res = WaitForSingleObject(pi.hProcess, 5);
} while (res == WAIT_TIMEOUT);
#ifndef THREADEDOUTPUT
//final part
TryTranslateOutput(hReadStdOut, hStdOutput);
TryTranslateOutput(hReadStdErr, hStdError);
#endif
TerminateThread(hInputThread, -1); //the process ended, no point in even writing there
CloseHandle(hInputThread);
#ifdef THREADEDOUTPUT
WaitForSingleObject(hOutputThread, INFINITE); //wait until it reads everything there is
CloseHandle(hOutputThread);
WaitForSingleObject(hErrorThread, INFINITE);
CloseHandle(hErrorThread);
#endif
CloseHandle(hWriteStdIn);
CloseHandle(hReadStdErr);
CloseHandle(hReadStdOut);
#endif
if (res != WAIT_OBJECT_0)
ThrowLastOsError(L"Cannot wait on the main process");
DWORD ExitCode = 0;
if (!GetExitCodeProcess(pi.hProcess, &ExitCode))
ThrowLastOsError(L"Cannot retrieve execution result");
CloseHandle(pi.hProcess);
return ExitCode;
}
示例12: U_TRACE_NO_PARAM
void UThread::close()
{
U_TRACE_NO_PARAM(0, "UThread::close()")
#ifdef _MSWINDOWS_
DWORD _tid = tid;
#else
pthread_t _tid = tid;
#endif
tid = 0;
U_INTERNAL_DUMP("tid = %p first = %p next = %p", _tid, first, next)
U_INTERNAL_ASSERT_POINTER(first)
UThread* obj;
UThread** ptr = &first;
while ((obj = *ptr))
{
U_INTERNAL_ASSERT_POINTER(obj)
# ifdef _MSWINDOWS_
if (tid == obj->tid)
# else
if (pthread_equal(tid, obj->tid))
# endif
{
U_INTERNAL_ASSERT_EQUALS(this, obj)
U_INTERNAL_ASSERT_EQUALS(next, obj->next)
*ptr = next;
next = 0;
break;
}
ptr = &(*ptr)->next;
}
if (_tid)
{
# ifdef _MSWINDOWS_ // wait for real w32 thread to cleanup
switch (cancel)
{
case cancelImmediate: TerminateThread((HANDLE)_tid, 0); break;
default: SetEvent(cancellation);
}
(void) WaitForSingleObject((HANDLE)_tid, INFINITE);
(void) U_SYSCALL(CloseHandle, "%p", cancellation);
(void) U_SYSCALL(CloseHandle, "%p", (HANDLE)_tid);
_endthreadex(0);
# else
# ifdef HAVE_PTHREAD_CANCEL
(void) U_SYSCALL(pthread_cancel, "%p", _tid);
# endif
if (detachstate == PTHREAD_CREATE_JOINABLE) (void) U_SYSCALL(pthread_join, "%p,%p", _tid, 0);
# ifdef HAVE_PTHREAD_YIELD
else
{
(void) U_SYSCALL_NO_PARAM(pthread_yield);
}
# endif
# endif
}
}
示例13: progress_callback
/*
* Callback for the run_with_progress_bar() function
*/
static LRESULT CALLBACK progress_callback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
HANDLE handle;
static int installation_time = 0; // active installation time, in secs
const int msg_max = ARRAYSIZE(progress_message);
static int msg_index = 0;
int i;
// coordinates that we want to disable (=> no resize)
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
switch (message) {
case WM_CREATE:
// Reset static variables
installation_time = 0;
msg_index = 0;
hProgress = hDlg;
// Start modal (disable parent Window)
EnableWindow(GetParent(hDlg), FALSE);
init_children(hProgress);
center_dialog(hProgress);
// Send a WM_TIMER message every second
SetTimer(hProgress, 1, 1000, NULL);
PostMessage(hProgress, UM_PROGRESS_START, 0, 0);
return (INT_PTR)TRUE;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for(i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case UM_PROGRESS_START:
if (progress_thid != -1L) {
wdi_err("program assertion failed - another operation is in progress");
} else {
// Using a thread prevents application freezout on security warning
progress_thid = _beginthread(progress_thread, 0, NULL);
if (progress_thid != -1L) {
return (INT_PTR)TRUE;
}
wdi_err("unable to create progress_thread");
}
// Fall through and return an error
wParam = (WPARAM)WDI_ERROR_RESOURCE;
case UM_PROGRESS_STOP:
// If you don't re-enable the parent Window before leaving
// all kind of bad things happen (other Windows get activated, etc.)
EnableWindow(GetParent(hDlg), TRUE);
PostQuitMessage((int)wParam);
DestroyWindow(hProgress);
return (INT_PTR)TRUE;
case WM_TIMER:
if (find_security_prompt() == NULL) {
installation_time++; // Only increment outside of security prompts
if ( (msg_index < msg_max) && (installation_time > 15*(msg_index+1)) ) {
// Change the progress blurb
SetWindowTextA(hProgressText, progress_message[msg_index]);
// Force a full redraw fot the transparent text background
ShowWindow(hProgressText, SW_HIDE);
UpdateWindow(hProgressText);
ShowWindow(hProgressText, SW_SHOW);
UpdateWindow(hProgressText);
msg_index++;
} else if ( (installation_time > 300) && (progress_thid != -1L) ) {
// Wait 300 (loose) seconds and kill the thread
// 300 secs is the timeout for driver installation on Vista
wdi_err("progress timeout expired - KILLING THREAD!");
handle = OpenThread(THREAD_TERMINATE, FALSE, (DWORD)progress_thid);
TerminateThread(handle, -1);
CloseHandle(handle);
PostQuitMessage(WDI_ERROR_TIMEOUT);
DestroyWindow(hProgress);
return (INT_PTR)FALSE;
}
}
return (INT_PTR)TRUE;
case WM_CLOSE: // prevent closure using Alt-F4
return (INT_PTR)TRUE;
case WM_DESTROY: // close application
hProgress = INVALID_HANDLE_VALUE;
return (INT_PTR)FALSE;
//.........这里部分代码省略.........
示例14: if
//.........这里部分代码省略.........
/* }
else
{*/
//if (m_hSpeechRecogThread)
//{
// CSimpleDict* pSimpleDict;
// m_pKinectWindow->GetSimpleDict(&pSimpleDict);
// pSimpleDict->~CSimpleDict();
// WaitForSingleObject(m_hSpeechRecogThread, 200);
// CloseHandle(m_hSpeechRecogThread);
// m_threadRun=false;
//}
//}
break;
////In-bed detection
case ID_FALLDETECTION:
if (!(pFallDetect->getIsRunFallDetect()))
{
pFallDetect->setIsRunFallDetect(TRUE);
if (!m_FallDetectThreadRun)
{
m_hFallDetectTxt2SpeechThread = CreateThread(NULL, 0, pFallDetect->Txt2SpeechStaticThread, (PVOID)pFallDetect, 0, 0);
m_FallDetectThreadRun = TRUE;
}
}
else
{
pFallDetect->setIsRunFallDetect(FALSE);
if (m_FallDetectThreadRun)
{
DWORD lpExitCode;
GetExitCodeThread(m_hFallDetectTxt2SpeechThread, &lpExitCode);
TerminateThread(m_hFallDetectTxt2SpeechThread, lpExitCode);
WaitForSingleObject(m_hFallDetectTxt2SpeechThread, 200);
CloseHandle(m_hFallDetectTxt2SpeechThread);
m_FallDetectThreadRun = FALSE;
}
}
break;
case ID_MOVEMENTDETECTION:
if (!(pFallDetect->getIsRunMovementDetect()))
{
pFallDetect->setIsRunMovementDetect(TRUE);
}
else
{
pFallDetect->setIsRunMovementDetect(FALSE);
}
break;
case ID_OUTOFBEDDETECTION:
break;
case ID_LYANGLEDETECTION:
if (!(pDepthInbedApps->getIsRunLyAngleDetect()))
{
pDepthInbedApps->setIsRunLyAngleDetect(TRUE);
}
else
{
pDepthInbedApps->setIsRunLyAngleDetect(FALSE);
}
break;
示例15: ConsoleCloseProc
static int
ConsoleCloseProc(
ClientData instanceData, /* Pointer to ConsoleInfo structure. */
Tcl_Interp *interp) /* For error reporting. */
{
ConsoleInfo *consolePtr = (ConsoleInfo *) instanceData;
int errorCode;
ConsoleInfo *infoPtr, **nextPtrPtr;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
DWORD exitCode;
errorCode = 0;
/*
* Clean up the background thread if necessary. Note that this must be
* done before we can close the file, since the thread may be blocking
* trying to read from the console.
*/
if (consolePtr->readThread) {
/*
* The thread may already have closed on it's own. Check it's exit
* code.
*/
GetExitCodeThread(consolePtr->readThread, &exitCode);
if (exitCode == STILL_ACTIVE) {
/*
* Set the stop event so that if the reader thread is blocked in
* ConsoleReaderThread on WaitForMultipleEvents, it will exit
* cleanly.
*/
SetEvent(consolePtr->stopReader);
/*
* Wait at most 20 milliseconds for the reader thread to close.
*/
if (WaitForSingleObject(consolePtr->readThread, 20)
== WAIT_TIMEOUT) {
/*
* Forcibly terminate the background thread as a last resort.
* Note that we need to guard against terminating the thread
* while it is in the middle of Tcl_ThreadAlert because it
* won't be able to release the notifier lock.
*/
Tcl_MutexLock(&consoleMutex);
/* BUG: this leaks memory. */
TerminateThread(consolePtr->readThread, 0);
Tcl_MutexUnlock(&consoleMutex);
}
}
CloseHandle(consolePtr->readThread);
CloseHandle(consolePtr->readable);
CloseHandle(consolePtr->startReader);
CloseHandle(consolePtr->stopReader);
consolePtr->readThread = NULL;
}
consolePtr->validMask &= ~TCL_READABLE;
/*
* Wait for the writer thread to finish the current buffer, then terminate
* the thread and close the handles. If the channel is nonblocking, there
* should be no pending write operations.
*/
if (consolePtr->writeThread) {
if (consolePtr->toWrite) {
/*
* We only need to wait if there is something to write. This may
* prevent infinite wait on exit. [python bug 216289]
*/
WaitForSingleObject(consolePtr->writable, INFINITE);
}
/*
* The thread may already have closed on it's own. Check it's exit
* code.
*/
GetExitCodeThread(consolePtr->writeThread, &exitCode);
if (exitCode == STILL_ACTIVE) {
/*
* Set the stop event so that if the reader thread is blocked in
* ConsoleWriterThread on WaitForMultipleEvents, it will exit
* cleanly.
*/
SetEvent(consolePtr->stopWriter);
/*
* Wait at most 20 milliseconds for the writer thread to close.
*/
//.........这里部分代码省略.........