static int iomtr_set_cpu_affinity(unsigned long affinity_mask) { int res = -1; #if defined(IOMTR_OS_LINUX) cpu_set_t s; int i, j; unsigned long t = 1; if (!affinity_mask) { affinity_mask = 1; } i = sizeof(unsigned long) * 8; if (i > CPU_SETSIZE) { i = CPU_SETSIZE; } CPU_ZERO (&s); for (j = 0; j < i; j++) if ((t << j) & affinity_mask) { CPU_SET(j, &s); break; } /* Developer Note: * * If meet compiling error about following line in a relatively old Linux system, * please try "sched_setaffinity(getpid(), &s)" instead. */ if (sched_setaffinity(getpid(), CPU_SETSIZE, &s) < 0) { cout << "Set CPU affinity fail." << errno << endl; if (errno == ENOSYS) { cout << "Warning: System does not support set CPU affinity." << endl; cout << "Be sure to check if measured results are reasonable." << endl; } } else { #ifdef _DEBUG cout << "Set CPU affinity sucessfully." << endl; #endif } #elif defined(IOMTR_OS_WIN32) || defined(IOMTR_OS_WIN64) if (!affinity_mask) { affinity_mask = 1; } // not &affinity_mask, MSDN API Doc error. res = SetProcessAffinityMask(GetCurrentProcess(), affinity_mask); if (!res) { res = GetLastError(); cout << "Set cpu affinity fail with" << res << endl; // default to CPU 1 res = SetProcessAffinityMask(GetCurrentProcess(), 1); } #elif defined(IOMTR_OS_NETWARE) || defined(IOMTR_OS_SOLARIS) // nop #else #warning ===> WARNING: You have to do some coding here to get the port done! #endif return res; }
Benchmark PriorityBoost::CanBoostPriority(void) { AutoCurrentContext ctxt; // Create two spinners and kick them off at the same time: AutoRequired<JustIncrementsANumber<ThreadPriority::BelowNormal>> lower; AutoRequired<JustIncrementsANumber<ThreadPriority::Normal>> higher; ctxt->Initiate(); #ifdef _MSC_VER // We want all of our threads to run on ONE cpu for awhile, and then we want to put it back at exit DWORD_PTR originalAffinity, systemAffinity; GetProcessAffinityMask(GetCurrentProcess(), &originalAffinity, &systemAffinity); SetProcessAffinityMask(GetCurrentProcess(), 1); auto onreturn = MakeAtExit([originalAffinity] { SetProcessAffinityMask(GetCurrentProcess(), originalAffinity); }); #else // TODO: Implement on Unix so that this benchmark is trustworthy #endif // Poke the conditional variable a lot: AutoRequired<std::mutex> contended; for(size_t i = 100; i--;) { // We sleep while holding contention lock to force waiting threads into the sleep queue. The reason we have to do // this is due to the way that mutex is implemented under the hood. The STL mutex uses a high-frequency variable // and attempts to perform a CAS (check-and-set) on this variable. If it succeeds, the lock is obtained; if it // fails, it will put the thread into a non-ready state by calling WaitForSingleObject on Windows or one of the // mutex_lock methods on Unix. // // When a thread can't be run, it's moved from the OS's ready queue to the sleep queue. The scheduler knows that // the thread can be moved back to the ready queue if a particular object is signalled, but in the case of a lock, // only one of the threads waiting on the object can actually be moved to the ready queue. It's at THIS POINT that // the operating system consults the thread priority--if only thread can be moved over, then the highest priority // thread will wind up in the ready queue every time. // // Thread priority does _not_ necessarily influence the amount of time the scheduler allocates allocated to a ready // thread with respect to other threads of the same process. This is why we hold the lock for a full millisecond, // in order to force the thread over to the sleep queue and ensure that the priority resolution mechanism is // directly tested. std::lock_guard<std::mutex> lk(*contended); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } // Need to terminate before we try running a comparison. ctxt->SignalTerminate(); return Benchmark { {"Low priority CPU time", std::chrono::nanoseconds{lower->val}}, {"High priority CPU time", std::chrono::nanoseconds{higher->val}}, }; }
void engine_open(engine_t * engine){ int affinity; char *my_dir; if( (my_dir = _getcwd( NULL, 0 )) == NULL ) my_fatal("Can't build path: %s\n",strerror(errno)); if(SetCurrentDirectory(option_get_string("EngineDir"))==0){ printf("tellusererror Polyglot:EngineDir error: %s\n",option_get_string("EngineDir")); fflush(stdout); Sleep(50000); my_fatal("EngineDir path error: %s\n",option_get_string("EngineDir")); } pipeEngine.Open(option_get_string("EngineCommand")); //play with affinity #ifndef NO_AFFINITY affinity=option_get_int("Affinity"); if(affinity!=-1){ my_log("POLYGLOT SetProcess Affinity\n"); SetProcessAffinityMask(child,affinity); // } #endif //lets go back SetCurrentDirectory(my_dir); // set priority if (option_get_bool("UseNice")){ my_log("POLYGLOT Adjust Engine Piority\n"); SetPriorityClass(child, GetWin32Priority(option_get_int("NiceValue"))); } }
void main(int argc, char *argv[]) { MSG msg; LARGE_INTEGER litmp; SetProcessAffinityMask(GetCurrentProcess(), 1); hInstance = GetModuleHandle(NULL); pHeapList.CessionNum = 1; pHeapList.HeapAlign = 0; pHeapList.HeapBottom = DjyosHeap; pHeapList.HeapTop = pHeapList.HeapBottom + sizeof(DjyosHeap); pHeapList.PageSize = 128; strcpy(pHeapList.name,"sys"); pHeapList.name[4] = '\0'; // a = CreateDirectory(_TEXT("djyfs"),NULL); // a = CreateDirectory(_TEXT("djyfs\\sys"),NULL); Heap_StaticModuleInit(0); Int_Init(); QueryPerformanceFrequency(&litmp); s64g_freq = litmp.QuadPart; Int_IsrConnect(cn_int_line_switch_context,switch_context); Int_SettoAsynSignal(cn_int_line_switch_context); //tick中断被设为异步信号 Int_RestoreAsynLine(cn_int_line_switch_context); // printf("VC 编译器版本:%d\n\r",_MSC_VER); Sys_Start(); // 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return ; }
static int hwloc_win_set_proc_cpubind(hwloc_topology_t topology __hwloc_attribute_unused, hwloc_pid_t proc, hwloc_const_bitmap_t hwloc_set, int flags) { DWORD_PTR mask; assert(nr_processor_groups == 1); if (flags & HWLOC_CPUBIND_NOMEMBIND) { errno = ENOSYS; return -1; } /* TODO: SetThreadGroupAffinity() for all threads doesn't enforce the whole process affinity, * maybe because of process-specific resource locality */ /* TODO: if we are in a single group (check with GetProcessGroupAffinity()), * SetProcessAffinityMask() changes the binding within that same group. */ /* TODO: NtSetInformationProcess() works very well for binding to any mask in a single group, * but it's an internal routine. */ /* TODO: checks whether hwloc-bind.c needs to pass INHERIT_PARENT_AFFINITY to CreateProcess() instead of execvp(). */ /* The resulting binding is always strict */ mask = hwloc_bitmap_to_ULONG_PTR(hwloc_set); if (!SetProcessAffinityMask(proc, mask)) return -1; return 0; }
static int precise_timer() { # ifdef NEKO_WINDOWS LARGE_INTEGER t; static LARGE_INTEGER freq; if( !init_done ) { DWORD procs, sm, procid = 1; // ensure that we always use the same processor // or else, performance counter might vary depending // on the current CPU GetProcessAffinityMask(GetCurrentProcess(),&procs,&sm); while( !(procs & procid) ) procid <<= 1; SetProcessAffinityMask(GetCurrentProcess(),procid); init_done = 1; QueryPerformanceFrequency(&freq); } QueryPerformanceCounter(&t); return (int)( t.QuadPart * 1000000 / freq.QuadPart ); # else static int base_sec; struct timeval tv; gettimeofday(&tv,NULL); if( !init_done ) { init_done = 1; base_sec = tv.tv_sec; } return (tv.tv_sec - base_sec) * 1000000 + tv.tv_usec; # endif }
// this sets the thread to run on the specific processors bool Thread::SetProcessors(CPUS const CPU) { if (m_ThreadHandle) { // get the current processor affinity mask HANDLE CurrentProcess=GetCurrentProcess(); DWORD ProcessAffinity, SystemAffinity; GetProcessAffinityMask(CurrentProcess, &ProcessAffinity, &SystemAffinity); // see if the current processors are set in the process affinity if ((CPU&ProcessAffinity)!=CPU) { // flags not set so add processor to process affinity // if they are allowed by the system affinity ProcessAffinity|=(CPU&SystemAffinity); if (!SetProcessAffinityMask(CurrentProcess, ProcessAffinity)) { return false; // failure } } // set the thread affinity if (!SetThreadAffinityMask(m_ThreadHandle, (CPU&SystemAffinity))) { return false; // failure } else { return true; // succuess } } else { // no thread return false; } }
void setNumCPUs(int num) { DWORD_PTR processAffinityMask; DWORD_PTR systemAffinityMask; if ( GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask, &systemAffinityMask) ) { // Count up the number of processes available for our app. int n = 0; for (int i = 0; i < sizeof(DWORD_PTR) * 4; i++) { if ( (systemAffinityMask & ((DWORD_PTR)1 << i)) ) n++; } // Limit max CPUs by user configuration. DWORD_PTR newAffinityMask = 0; if ( num < n ) { int m = 0; for (int i = 0; i < sizeof(DWORD_PTR) * 4; i++) { if ( (systemAffinityMask & ((DWORD_PTR)1 << i)) ) { newAffinityMask |= ((DWORD_PTR)1 << i); m++; if ( m == num ) break; } } newAffinityMask <<= (n - num); } else { newAffinityMask = systemAffinityMask; } // Set new affinity mask. SetProcessAffinityMask(GetCurrentProcess(), newAffinityMask); } }
/** * @brief Switch to one processor usage for windows system with more than * one processor */ void Sys_SetAffinityAndPriority (void) { SYSTEM_INFO sysInfo; /* 1 - use core #0 * 2 - use core #1 * 3 - use cores #0 and #1 */ HANDLE proc = GetCurrentProcess(); if (sys_priority->modified) { if (sys_priority->integer < 0) Cvar_SetValue("sys_priority", 0); else if (sys_priority->integer > 2) Cvar_SetValue("sys_priority", 2); sys_priority->modified = false; switch (sys_priority->integer) { case 0: SetPriorityClass(proc, NORMAL_PRIORITY_CLASS); Com_Printf("Priority changed to NORMAL\n"); break; case 1: SetPriorityClass(proc, HIGH_PRIORITY_CLASS); Com_Printf("Priority changed to HIGH\n"); break; default: SetPriorityClass(proc, REALTIME_PRIORITY_CLASS); Com_Printf("Priority changed to REALTIME\n"); break; } } if (sys_affinity->modified) { DWORD_PTR procAffinity = 0; GetSystemInfo(&sysInfo); Com_Printf("Found %i processors\n", (int)sysInfo.dwNumberOfProcessors); sys_affinity->modified = false; if (sysInfo.dwNumberOfProcessors >= 2) { switch (sys_affinity->integer) { case 0: Com_Printf("Use all cores\n"); procAffinity = (1 << sysInfo.dwNumberOfProcessors) - 1; break; case 1: Com_Printf("Use two cores\n"); procAffinity = 3; break; case 2: Com_Printf("Only use one core\n"); procAffinity = 1; break; } } else { Com_Printf("...only found one processor\n"); } SetProcessAffinityMask(proc, procAffinity); } CloseHandle(proc); }
unsigned WINAPI SetCpuAffinity_tt(void * pParam) { DWORD_PTR mask = 0L; int cpu_z = GetNumberOfWorkers(); /* 设置进程总是在除开CPU0之外的其他核心运行 */ switch (cpu_z) { case 2: mask = 0x02; break; case 3: mask = 0x06; break; case 4: mask = 0x0e; break; case 6: mask = 0x3e; break; case 8: mask = 0xfe; break; default: break; } if (mask) { SetProcessAffinityMask(GetCurrentProcess(),mask); } return (1); }
int NT_set_process_priority(void) { DWORD SingleCPUMask = 0; DWORD ProcessAffinityMask, SystemAffinityMask; if (!GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask, & SystemAffinityMask)) msyslog(LOG_ERR, "GetProcessAffinityMask: %m"); else { SingleCPUMask = 1; # ifdef DEBUG msyslog(LOG_INFO, "System AffinityMask = %x", SystemAffinityMask); # endif } while (SingleCPUMask && !(SingleCPUMask & SystemAffinityMask)) SingleCPUMask = SingleCPUMask << 1; if (!SingleCPUMask) msyslog(LOG_ERR, "Can't set Processor Affinity Mask"); else if (!SetProcessAffinityMask(GetCurrentProcess(), SingleCPUMask)) msyslog(LOG_ERR, "SetProcessAffinityMask: %m"); # ifdef DEBUG else msyslog(LOG_INFO,"ProcessorAffinity Mask: %x", SingleCPUMask ); # endif if (!SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)) { msyslog(LOG_ERR, "SetPriorityClass: %m"); return 0; } else return 1; }
/* CPU affinity mask buffer instead, as the present code will fail beyond 32 CPUs */ int set_cpu_affinity(unsigned int cpuid) { unsigned long mask = 0xffffffff; unsigned int len = sizeof(mask); int retValue = 0; int pid; #ifdef _WIN32 HANDLE hProcess; #endif #ifdef _WIN32 SET_MASK(cpuid) hProcess = GetCurrentProcess(); if (SetProcessAffinityMask(hProcess, mask) == 0) { return -1; } #elif CMK_HAS_BINDPROCESSOR pid = getpid(); if (bindprocessor(BINDPROCESS, pid, cpuid) == -1) return -1; #else #ifdef CPU_ALLOC if ( cpuid >= CPU_SETSIZE ) { cpu_set_t *cpusetp; size_t size; int num_cpus; num_cpus = cpuid + 1; cpusetp = CPU_ALLOC(num_cpus); if (cpusetp == NULL) { perror("set_cpu_affinity CPU_ALLOC"); return -1; } size = CPU_ALLOC_SIZE(num_cpus); CPU_ZERO_S(size, cpusetp); CPU_SET_S(cpuid, size, cpusetp); if (sched_setaffinity(0, size, cpusetp) < 0) { perror("sched_setaffinity dynamically allocated"); CPU_FREE(cpusetp); return -1; } CPU_FREE(cpusetp); } else #endif { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(cpuid, &cpuset); /*SET_MASK(cpuid)*/ /* PID 0 refers to the current process */ /*if (sched_setaffinity(0, len, &mask) < 0) {*/ if (sched_setaffinity(0, sizeof(cpuset), &cpuset) < 0) { perror("sched_setaffinity"); return -1; } } #endif return 0; }
VOID SetExecutionOnCore0() { DWORD_PTR mask = 1; SetProcessAffinityMask( GetCurrentProcess(), mask ); }
vm_status vm_affinity_process_set(VM_PID pid, vm_affinity_mask *mptr) { if(!mptr) return VM_NULL_PTR; if(SetProcessAffinityMask(pid, mptr[0].mskbits[0])) return VM_OK; return VM_OPERATION_FAILED; }
void setCPUAffinity(uint32_t mask) { DWORD_PTR processAffinityMask; DWORD_PTR systemAffinityMask; // Get system mask. GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask, &systemAffinityMask); // Set new affinity mask. SetProcessAffinityMask(GetCurrentProcess(), mask & systemAffinityMask); }
// based on Smod code static void Com_SetProcessorAffinity( void ) { #ifdef _WIN32 DWORD processMask; if ( sscanf( com_affinity->string, "%X", &processMask ) != 1 ) processMask = 1; // set to first core only if ( !SetProcessAffinityMask( GetCurrentProcess(), processMask ) ) Com_Printf( "Setting affinity mask failed (%s)\n", GetErrorString( GetLastError() ) ); #endif }
int set_mp() { SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); if(SystemInfo.dwNumberOfProcessors <= 1) return 0; BOOL ret = SetProcessAffinityMask(GetCurrentProcess(), SystemInfo.dwActiveProcessorMask); return ret ? 0 : -1; }
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR lpCmdLine, int nCmdShow ) { STARTUPINFO si = {0,}; PROCESS_INFORMATION pi = {0,}; si.cb = sizeof(si); CreateProcess(NULL, lpCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); SetProcessAffinityMask(pi.hProcess, 1); return 0; }
LUALIB_FUNCTION(window, SetAffinity) { auto window = (HWND)gEnv->pRenderer->GetHWND(); LPDWORD process = nullptr; GetWindowThreadProcessId(window, process); SetProcessAffinityMask(process, my->ToNumber(1)); return 0; }
void I_SetAffinityMask(void) { unsigned int process_affinity_mask = DEFAULT_AFFINITY_MASK; int p = M_CheckParm("-affinity"); if (p && p < myargc-1) process_affinity_mask = atoi(myargv[p+1]); // Set the process affinity mask so that all threads // run on the same processor. This is a workaround for a bug in // SDL_mixer that causes occasional crashes. if (process_affinity_mask) { const char *errbuf = NULL; #ifdef _WIN32 if (!SetProcessAffinityMask(GetCurrentProcess(), process_affinity_mask)) { errbuf = WINError(); } #elif defined(HAVE_SCHED_SETAFFINITY) // POSIX version: int i; { cpu_set_t set; CPU_ZERO(&set); for(i = 0; i < 16; i++) { CPU_SET((process_affinity_mask>>i)&1, &set); } if (sched_setaffinity(getpid(), sizeof(set), &set) == -1) { errbuf = strerror(errno); } } #else return; #endif if (errbuf == NULL) { lprintf(LO_INFO, "I_SetAffinityMask: manual affinity mask is %d\n", process_affinity_mask); } else { lprintf(LO_ERROR, "I_SetAffinityMask: failed to set process affinity mask (%s)\n", errbuf); } } }
void newfunc_newhandler08_init(void) { TIMECAPS tc; timeGetDevCaps(&tc,sizeof(tc)); if(tc.wPeriodMin<1) tc.wPeriodMin=1; int08_timer_period=(long)(1000.0/(float)INT08_CYCLES_NEW); if(int08_timer_period<=tc.wPeriodMin) int08_timer_period=tc.wPeriodMin; timeBeginPeriod(int08_timer_period); #ifndef MPXPLAY_USE_SMP { HANDLE curr_process=GetCurrentProcess(); if(curr_process) SetProcessAffinityMask(curr_process,MPXPLAY_THREAD_AFFINITY_MASK); } #endif if(!int08_timer_thread_handle){ int08_timer_thread_handle=(HANDLE)_beginthreadex(NULL,0,(void *)newhandler_08_timer_thread,NULL,CREATE_SUSPENDED,NULL); if(int08_timer_thread_handle){ SetThreadPriority(int08_timer_thread_handle,THREAD_PRIORITY_HIGHEST); SetSecurityInfo(int08_timer_thread_handle,SE_KERNEL_OBJECT,MPXPLAY_INT08THREAD_RIGHTS,NULL,NULL,NULL,NULL); #ifndef MPXPLAY_USE_SMP SetThreadAffinityMask(int08_timer_thread_handle,MPXPLAY_THREAD_AFFINITY_MASK); #endif ResumeThread(int08_timer_thread_handle); }else{ } } if(!int08_thread_handle){ int08_thread_handle=(HANDLE)_beginthreadex(NULL,0,(void *)newhandler_08_thread,NULL,CREATE_SUSPENDED,NULL); if(int08_thread_handle){ SetThreadPriority(int08_thread_handle,THREAD_PRIORITY_HIGHEST); SetSecurityInfo(int08_thread_handle,SE_KERNEL_OBJECT,MPXPLAY_INT08THREAD_RIGHTS,NULL,NULL,NULL,NULL); #ifndef MPXPLAY_USE_SMP SetThreadAffinityMask(int08_thread_handle,MPXPLAY_THREAD_AFFINITY_MASK); #endif ResumeThread(int08_thread_handle); }else{ } } }
void pypy_setup_profiling() { if (!profiling_setup) { DWORD_PTR affinity_mask, system_affinity_mask; GetProcessAffinityMask(GetCurrentProcess(), &base_affinity_mask, &system_affinity_mask); affinity_mask = 1; /* Pick one cpu allowed by the system */ if (system_affinity_mask) while ((affinity_mask & system_affinity_mask) == 0) affinity_mask <<= 1; SetProcessAffinityMask(GetCurrentProcess(), affinity_mask); profiling_setup = 1; } }
void os_init() { ThreadCritical::intialize(); Thread::initialize(); if (hInstance == NULL) { hInstance = GetModuleHandle(NULL); nCmdShow = SW_SHOWNORMAL; } os::initialize_system_info(); //%todo: remove this processor affinity stuff ULONG systemMask; ULONG processMask; GetProcessAffinityMask(GetCurrentProcess(), &processMask, &systemMask); ULONG processorId = 1; while (!(processMask & processorId) && processorId < processMask) processorId >>= 1; std->print_cr("processor: %ld", processorId); if (!SetProcessAffinityMask(GetCurrentProcess(), processorId)) std->print_cr("error code: %d", GetLastError()); // end processor affinity - for removal SetConsoleCtrlHandler(&HandlerRoutine, TRUE); HANDLE threadHandle; // Initialize main_process and main_thread main_process = GetCurrentProcess(); // Remember main_process is a pseudo handle if (!DuplicateHandle(main_process, GetCurrentThread(), main_process, &threadHandle, THREAD_ALL_ACCESS, FALSE, 0)) { fatal("DuplicateHandle failed\n"); } main_thread_id = (int) GetCurrentThreadId(); main_thread = new Thread(threadHandle, main_thread_id, NULL); // Setup Windows Exceptions SetUnhandledExceptionFilter(topLevelExceptionFilter); // Create the watcher thread if (EnableTasks) { DWORD watcher_id; watcher_thread = CreateThread(NULL, 0, &WatcherMain, 0, 0, &watcher_id); SetThreadPriority(watcher_thread, THREAD_PRIORITY_HIGHEST); } }
/** * Set process priority and affinity to use all cpu's but the first one. * This improves benchmark results on a multi-cpu systems. * * @deprecated This function shall be removed soon. */ static void benchmark_cpu_init(void) { DWORD_PTR dwProcessMask, dwSysMask, dwDesired; SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); if ( GetProcessAffinityMask(GetCurrentProcess(), &dwProcessMask, &dwSysMask) ) { dwDesired = dwSysMask & (dwProcessMask & ~1); /* remove the first processor */ dwDesired = (dwDesired ? dwDesired : dwSysMask & ~1); if (dwDesired != 0) { SetProcessAffinityMask(GetCurrentProcess(), dwDesired); } } }
// OSInitHookBegin *********************************************************** // This hook is invoked at the beginning of the OS initialization. MUST NOT BE DEFINED BY THE APPLICATION. void OSInitHookBegin() { int i; char temp[256]; static BOOLEAN isInitialized = FALSE; DBGPRINT(0x00000010, "*** OSInitHookBegin\n"); if (isInitialized) { for (i=0; i < OS_LOWEST_PRIO + 2; i++) { if (hTaskThread[i]) { if (TerminateThread(hTaskThread[i], 0)==FALSE) { printf("ERROR: Terminate thread for task %d (in OSInitHookBegin) %Xh\n", i, GetLastError()); } CloseHandle(hTaskThread[i]); } hTaskThread[i]=NULL; taskSuspended[i]=0; pTaskTcb[i]=NULL; } return; } else { isInitialized=TRUE; } SetProcessAffinityMask(GetCurrentProcess(), 0x1); // dwProcessAffinityMask -> 1 = run only on CPU 0 hScheduleEvent = CreateEvent(NULL, FALSE, FALSE, NULL); //Create the scheduler and interrupt event for (i=0; i< NINTERRUPTS; i++) { sprintf(temp,"OSirq%u",i); hInterruptEvent[i] = CreateEvent(NULL, TRUE, FALSE, temp); interruptTable[i] = OSDummyISR; } InitializeCriticalSection(&criticalSection); hScheduleThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) OSScheduleThread, NULL, 0, (INT32U*) &i); //Create the scheduler and interrupt thread hInterruptThread= CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) OSInterruptThread, NULL, 0, &interruptThreadId); interruptTable[0] = OSTimeTick; SetPriorityClass( hScheduleThread, THREAD_PRIORITY_HIGHEST);//Set the scheduler and interrupt threads to maximum WIN32 priority SetThreadPriority(hScheduleThread, THREAD_PRIORITY_TIME_CRITICAL); SetPriorityClass( hInterruptThread, THREAD_PRIORITY_HIGHEST); SetThreadPriority(hInterruptThread, THREAD_PRIORITY_HIGHEST); SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlBreakHandler, TRUE); Sleep(0); //Give Windows a chance to start the scheduler and interrupt thread //ADD YOUR OWN HOOK CODE HERE IF NECESSARY }
void Sys_SetProcessProperties(void) { #ifdef SET_PROCESS_AFFINITY DWORD_PTR processAffinityMask; DWORD_PTR systemAffinityMask; int core, bit, currentCore; BOOL success; #endif HANDLE process = GetCurrentProcess(); //Set Process priority SetPriorityClass(process, HIGH_PRIORITY_CLASS); #ifdef SET_PROCESS_AFFINITY if (!GetProcessAffinityMask(process, &processAffinityMask, &systemAffinityMask)) { return; } //set this to the core you want your process to run on // probably could catch this from a cvar, but do we want people f*****g arround with it core = SET_PROCESS_AFFINITY; for (bit = 0, currentCore = 1; bit < 64; bit++) { if (BIT(bit) & processAffinityMask) { if (currentCore != core) { CLEARBIT(processAffinityMask, bit); } currentCore++; } } success = SetProcessAffinityMask(process, processAffinityMask); if (success) { //Yup great Com_DPrintf(S_COLOR_GREEN "Sys_SetProcessProperties succesfully set process affinity"); } else { //F**k! Com_DPrintf(S_COLOR_RED "Sys_SetProcessProperties failed to set process affinity"); } #endif }
void Sys_SetProcessProperties(void) { #if 0 DWORD_PTR processAffinityMask; DWORD_PTR systemAffinityMask; DWORD_PTR mask; int core, bit, currentCore; BOOL success; #endif HANDLE process = GetCurrentProcess(); //Set Process priority SetPriorityClass(process, HIGH_PRIORITY_CLASS); #if 0 //This could be fixed & enabled in the future, but now it just causes input issues if (!GetProcessAffinityMask(process, &processAffinityMask, &systemAffinityMask)) { return; } //set this to the core you want your process to run on core = 2; mask = 0x1; for (bit = 0, currentCore = 1; bit < 64; bit++) { if (mask & processAffinityMask) { if (currentCore != core) { processAffinityMask &= ~mask; } currentCore++; } mask = mask << 1; } success = SetProcessAffinityMask(process, processAffinityMask); if (success) { //Yup great } else { //F**k! } #endif }
void Sys_SetProcessorAffinity( void ) { DWORD_PTR processMask, dummy; HANDLE handle = GetCurrentProcess(); if ( !GetProcessAffinityMask( handle, &dummy, &dummy ) ) return; if ( sscanf( com_affinity->string, "%X", &processMask ) != 1 ) processMask = 1; // set to first core only if ( !processMask ) return; if ( !SetProcessAffinityMask( handle, processMask ) ) Com_DPrintf( "Setting affinity mask failed (%s)\n", GetErrorString( GetLastError() ) ); }
int TestMain () { #if _WIN32||_WIN64 || __linux__ || __FreeBSD_version >= 701000 #if _WIN32||_WIN64 SYSTEM_INFO si; GetSystemInfo(&si); if ( si.dwNumberOfProcessors < 2 ) return Harness::Skipped; int availableProcs = (int)si.dwNumberOfProcessors / 2; DWORD_PTR mask = 1; for ( int i = 1; i < availableProcs; ++i ) mask |= mask << 1; bool err = !SetProcessAffinityMask( GetCurrentProcess(), mask ); #else /* !WIN */ #if __linux__ int maxProcs = get_nprocs(); typedef cpu_set_t mask_t; #if __TBB_MAIN_THREAD_AFFINITY_BROKEN #define setaffinity(mask) sched_setaffinity(0 /*get the mask of the calling thread*/, sizeof(mask_t), &mask) #else #define setaffinity(mask) sched_setaffinity(getpid(), sizeof(mask_t), &mask) #endif #else /* __FreeBSD__ */ int maxProcs = sysconf(_SC_NPROCESSORS_ONLN); typedef cpuset_t mask_t; #if __TBB_MAIN_THREAD_AFFINITY_BROKEN #define setaffinity(mask) cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask_t), &mask) #else #define setaffinity(mask) cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(mask_t), &mask) #endif #endif /* __FreeBSD__ */ if ( maxProcs < 2 ) return Harness::Skipped; mask_t newMask; CPU_ZERO(&newMask); int availableProcs = min(maxProcs, (int)sizeof(mask_t) * CHAR_BIT) / 2; for ( int i = 0; i < availableProcs; ++i ) CPU_SET( i, &newMask ); int err = setaffinity( newMask ); #endif /* !WIN */ ASSERT( !err, "Setting process affinity failed" ); ASSERT( tbb::task_scheduler_init::default_num_threads() == availableProcs, NULL ); ASSERT( (int)tbb::tbb_thread::hardware_concurrency() == availableProcs, NULL ); return Harness::Done; #else /* !(WIN || LIN || BSD) */ return Harness::Skipped; #endif /* !(WIN || LIN || BSD) */ }
void VCInit(void) { HANDLE cp,ct; cp = GetCurrentProcess(); //得到当前进程句柄 ct = GetCurrentThread(); //得到当前线程伪句柄 SetProcessAffinityMask(cp, 1L); //Select the first CPU #if FP_SAVE_RESTORE_EN > 0u Context.ContextFlags = CONTEXT_FULL; //Don't need to save CONTEXT_FLOATING_POINT #else Context.ContextFlags = (CONTEXT_FULL | CONTEXT_FLOATING_POINT); //Important #endif DuplicateHandle(cp, ct, cp, &MainHandle, 0, TRUE, 2); //伪句柄转换,得到线程真句柄 }