/// <summary> /// Set manual affinity, use native function depending of the Operating system. /// </summary> /// <param name="threadAffinity"></param> public static void SetManualAffinity(string threadAffinity) { try { ulong handle = Convert.ToUInt64(threadAffinity, 16); if (Environment.OSVersion.Platform == PlatformID.Unix) // Linux/UNIX { sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref handle); } else { Thread.BeginThreadAffinity(); int threadId = GetCurrentThreadId(); ProcessThread thread = Process.GetCurrentProcess().Threads.Cast <ProcessThread>() .Single(t => t.Id == threadId); thread.ProcessorAffinity = (IntPtr)handle; SetThreadAffinityMask((IntPtr)threadId, (IntPtr)handle); } } catch (Exception error) { ClassConsole.WriteLine( "Cannot apply Manual Affinity with: " + threadAffinity + " | Exception: " + error.Message, 3); } }
void BwDoWork(object sender, DoWorkEventArgs e) { var bw = sender as BackgroundWorker; var args = e.Argument as WorkerArgs; try { Thread.BeginThreadAffinity(); ulong affinity = 1UL << args.threadIdx; CurrentThread.ProcessorAffinity = (IntPtr)affinity; while (!bw.CancellationPending) { int taskManagerBitmapIdx = mTaskManagerLogicalProcessorIdxToProcessThreadId[args.threadIdx]; if (0 != (mPattern & (1UL << taskManagerBitmapIdx))) { HeavyLifting(args.threadIdx); } else { Thread.Sleep(SLEEP_MS); } } e.Cancel = true; //Console.WriteLine("{0} Canceled", args.threadIdx); } finally { Thread.EndThreadAffinity(); } }
/// <summary> /// Set automatic affinity, use native function depending of the Operating system. /// </summary> /// <param name="threadIdMining"></param> public static void SetAffinity(int threadIdMining) { try { if (Environment.OSVersion.Platform == PlatformID.Unix) // Linux/UNIX { if (Environment.ProcessorCount > threadIdMining && threadIdMining >= 0) { ulong processorMask = 1UL << threadIdMining; sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref processorMask); } } else { if (Environment.ProcessorCount > threadIdMining && threadIdMining >= 0) { Thread.BeginThreadAffinity(); int threadId = GetCurrentThreadId(); ProcessThread thread = Process.GetCurrentProcess().Threads.Cast <ProcessThread>() .Single(t => t.Id == threadId); ulong cpuMask = 1UL << threadIdMining; thread.ProcessorAffinity = (IntPtr)cpuMask; SetThreadAffinityMask((IntPtr)threadIdMining, (IntPtr)cpuMask); } } } catch (Exception error) { ClassConsole.WriteLine( "Cannot apply Automatic Affinity with thread id: " + threadIdMining + " | Exception: " + error.Message, 3); } }
/// <summary> /// Process the records sequentially. This method tries /// to lock a record and moves to the next record if /// it fails to get the lock. /// </summary> public void DoWork() { Thread.BeginThreadAffinity(); // We must be in a transaction for locking to work. using (var transaction = new Transaction(this.sesid)) { if (Api.TryMoveFirst(this.sesid, this.tableid)) { do { // Getting a lock in ESENT is instantaneous -- if // another thread has the record locked or has // updated this record, this call will fail. There // is no way to wait for the lock to be released. // (because ESENT uses Snapshot Isolation the other // session's lock will always be visible until this // transaction commits). if (Api.TryGetLock(this.sesid, this.tableid, GetLockGrbit.Write)) { // [Do something] Thread.Sleep(1); Api.JetDelete(this.sesid, this.tableid); this.RecordsProcessed++; } }while (Api.TryMoveNext(this.sesid, this.tableid)); } transaction.Commit(CommitTransactionGrbit.LazyFlush); } Thread.EndThreadAffinity(); }
private static void SetThreadAffinity(int index) { if (IsRunningOnMono) { return; } try { Thread.BeginThreadAffinity(); var affinity = GetAffinity(index + 1, Environment.ProcessorCount); var thread = GetCurrentThread(); thread.ProcessorAffinity = new IntPtr(1 << affinity); } catch (Exception) { var logger = Logger.Setup(); logger.Write($"Could not set Task to run on second Core or Processor", LogLevel.Error, "ThreadHelper"); } // Prevents "Normal" processes from interrupting Threads var process = Process.GetCurrentProcess(); process.PriorityClass = ProcessPriorityClass.High; }
/// <summary> /// Enters lock. /// </summary> /// <param name="permitIntraLevel">Can same level be used.</param> /// <param name="millisecondsTimeout">Timeout to enter lock.</param> /// <returns><see cref="IDisposable"/> to use in using statement.</returns> public IDisposable Enter(bool permitIntraLevel, int millisecondsTimeout) { Thread.BeginThreadAffinity(); Thread.BeginCriticalRegion(); bool taken = false; try { PushLevel(permitIntraLevel); taken = Monitor.TryEnter(_lock, millisecondsTimeout); if (!taken) { throw new TimeoutException("Timeout occurred while attempting to acquire monitor"); } } finally { if (!taken) { Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); } } return(new LeveledLockCookie(this)); }
public static IDisposable SetThreadAffinity(int threadCount = 1, bool assignEvenly = false) { Contract.Assert(threadCount > 0, nameof(threadCount) + " must be greater than zero!"); Contract.EndContractBlock(); var original = new RefValue <IntPtr>(); return (new ManagedDelegateDisposable( () => { var mask = CalculateAffinityMask(threadCount, assignEvenly); // disabling .NET thread management Thread.BeginThreadAffinity(); // setting correctly affinity original.Value = SetThreadAffinityMask(GetCurrentThread(), new IntPtr(mask)); if (original.Value == IntPtr.Zero) { original.Value = Process.GetCurrentProcess().ProcessorAffinity; } }, () => { // reverting to process affinity SetThreadAffinityMask(GetCurrentThread(), original.Value); // enabling .NET thread management Thread.EndThreadAffinity(); })); }
private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut) { RuntimeHelpers.PrepareConstrainedRegions(); bool result; try { } finally { Thread.BeginCriticalRegion(); Thread.BeginThreadAffinity(); int num = SharedUtils.WaitForSingleObjectDontCallThis(mutexIn.SafeWaitHandle, 500); int num2 = num; if (num2 != 0 && num2 != 128) { result = (num2 == 258); } else { mutexOut = mutexIn; result = true; } if (mutexOut == null) { Thread.EndThreadAffinity(); Thread.EndCriticalRegion(); } } return(result); }
private void WorkLoop() { if (FixedCore) { Thread.BeginThreadAffinity(); CurrentThread.ProcessorAffinity = new IntPtr(1 << m_coreID); } while (true) { m_lock.WaitOne(); if (m_abort) { m_resetEvent.Set(); if (FixedCore) { Thread.EndThreadAffinity(); } return; } m_calculationAlogrithm.Calculate(m_resource); m_resource.Dispose(); m_resetEvent.Set(); } }
public Game1() { // Define the VR window properties graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 800; graphics.SynchronizeWithVerticalRetrace = false; graphics.PreferMultiSampling = true; graphics.GraphicsProfile = GraphicsProfile.HiDef; this.TargetElapsedTime = TimeSpan.FromTicks(333); graphics.ApplyChanges(); // Set application priority to maximum Content.RootDirectory = "Content"; Process process = Process.GetCurrentProcess(); process.PriorityClass = ProcessPriorityClass.RealTime; process.PriorityBoostEnabled = true; // Set current Thread to maximum priority Thread t = Thread.CurrentThread; t.Priority = ThreadPriority.Highest; Thread.BeginThreadAffinity(); SetForegroundWindow(this.Window.Handle); // Set the location of the VR window var form = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(this.Window.Handle); form.TopMost = true; form.Location = new System.Drawing.Point(-1280, 0); }
public static void MiscellaneousTest() { Thread.BeginCriticalRegion(); Thread.EndCriticalRegion(); Thread.BeginThreadAffinity(); Thread.EndThreadAffinity(); ThreadTestHelpers.RunTestInBackgroundThread(() => { // TODO: Port tests for these once all of the necessary interop APIs are available Thread.CurrentThread.DisableComObjectEagerCleanup(); Marshal.CleanupUnusedObjectsInCurrentContext(); }); #pragma warning disable 618 // obsolete members Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack()); Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture())); #pragma warning restore 618 // obsolete members Thread.MemoryBarrier(); var ad = Thread.GetDomain(); Assert.NotNull(ad); Assert.Equal(AppDomain.CurrentDomain, ad); Assert.Equal(ad.Id, Thread.GetDomainID()); Thread.SpinWait(int.MinValue); Thread.SpinWait(-1); Thread.SpinWait(0); Thread.SpinWait(1); Thread.Yield(); }
private double EstimateMaxClock(double timeWindow) { long ticks = (long)(timeWindow * Stopwatch.Frequency); uint lsbBegin, msbBegin, lsbEnd, msbEnd; Thread.BeginThreadAffinity(); long timeBegin = Stopwatch.GetTimestamp() + (long)Math.Ceiling(0.001 * ticks); long timeEnd = timeBegin + ticks; while (Stopwatch.GetTimestamp() < timeBegin) { } WinRing0.Rdtsc(out lsbBegin, out msbBegin); while (Stopwatch.GetTimestamp() < timeEnd) { } WinRing0.Rdtsc(out lsbEnd, out msbEnd); Thread.EndThreadAffinity(); ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin; ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd; return((((double)(countEnd - countBegin)) * Stopwatch.Frequency) / (timeEnd - timeBegin)); }
public static void MiscellaneousTest() { Thread.BeginCriticalRegion(); Thread.EndCriticalRegion(); Thread.BeginThreadAffinity(); Thread.EndThreadAffinity(); #pragma warning disable 618 // obsolete members Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack()); Assert.Throws <InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture())); #pragma warning restore 618 // obsolete members Thread.MemoryBarrier(); var ad = Thread.GetDomain(); Assert.NotNull(ad); Assert.Equal(AppDomain.CurrentDomain, ad); Assert.Equal(ad.Id, Thread.GetDomainID()); Thread.SpinWait(int.MinValue); Thread.SpinWait(-1); Thread.SpinWait(0); Thread.SpinWait(1); Thread.Yield(); }
private static void RunPhysicalCompletions(object state) { var thread = ((RioThread)state); #if NET451 Thread.BeginThreadAffinity(); #endif var nativeThread = GetCurrentThread(); var affinity = GetAffinity(thread._id); nativeThread.ProcessorAffinity = new IntPtr((long)affinity); thread._connections = new Dictionary <long, RioTcpConnection>(); thread._bufferIdMappings = new List <BufferMapping>(); var memoryPool = new MemoryPool(); memoryPool.RegisterSlabAllocationCallback((slab) => thread.OnSlabAllocated(slab)); memoryPool.RegisterSlabDeallocationCallback((slab) => thread.OnSlabDeallocated(slab)); thread._factory = new PipeFactory(memoryPool); thread.ProcessPhysicalCompletions(); #if NET451 Thread.EndThreadAffinity(); #endif }
public void Setup() { this.instance = new Instance(Guid.NewGuid().ToString(), "RetrieveColumnsPerfTest"); this.instance.Parameters.NoInformationEvent = true; this.instance.Parameters.Recovery = false; this.instance.Init(); this.session = new Session(this.instance); // turn off logging so initialization is faster this.columnidDict = SetupHelper.CreateTempTableWithAllColumns(this.session, TempTableGrbit.ForceMaterialization, out this.tableid); // Insert a record and position the tableid on it using (var transaction = new Transaction(this.session)) using (var update = new Update(this.session, this.tableid, JET_prep.Insert)) { Api.SetColumn(this.session, this.tableid, this.columnidDict["boolean"], this.expectedBool); Api.SetColumn(this.session, this.tableid, this.columnidDict["int32"], this.expectedInt32); Api.SetColumn(this.session, this.tableid, this.columnidDict["int64"], this.expectedInt64); Api.SetColumn(this.session, this.tableid, this.columnidDict["guid"], this.expectedGuid); Api.SetColumn(this.session, this.tableid, this.columnidDict["unicode"], this.expectedString, Encoding.Unicode); update.Save(); transaction.Commit(CommitTransactionGrbit.None); } Api.TryMoveFirst(this.session, this.tableid); Thread.CurrentThread.Priority = ThreadPriority.Highest; Thread.BeginThreadAffinity(); }
static void EsquentaP(object numero_obj) { int i = 0; DateTime ultimo = DateTime.Now; if (affinity) { Thread.BeginThreadAffinity(); CurrentThread.ProcessorAffinity = new IntPtr(1); } try { while (true) { i++; if (i == int.MaxValue) { i = 0; var lps = int.MaxValue / (DateTime.Now - ultimo).TotalSeconds / 1000000; Console.WriteLine("Thread " + numero_obj + " " + lps.ToString("0.000") + " M loops/s"); ultimo = DateTime.Now; } } } finally { Thread.EndThreadAffinity(); } }
///<summary> ///</summary> ///<exception cref="ArgumentNullException"></exception> public DocumentSessionScope(IDocumentSession session) { _instance = session; Thread.BeginThreadAffinity(); _head = this; }
public void VerifyJetSetSessionContextAllowsThreadMigration() { using (var instance = new Instance("JetSetSessionContext")) { SetupHelper.SetLightweightConfiguration(instance); instance.Init(); using (var session = new Session(instance)) { // Without the calls to JetSetSessionContext/JetResetSessionContext // this will generate a session sharing violation. var context = new IntPtr(Any.Int32); var thread = new Thread(() => { Thread.BeginThreadAffinity(); Api.JetSetSessionContext(session, context); Api.JetBeginTransaction(session); Api.JetResetSessionContext(session); Thread.EndThreadAffinity(); }); thread.Start(); thread.Join(); Api.JetSetSessionContext(session, context); Api.JetCommitTransaction(session, CommitTransactionGrbit.None); Api.JetResetSessionContext(session); } } }
/// <summary> /// Determines the name of a object handle. /// </summary> public void DoWork() { // Notify the CLR that this thread may not be re-scheduled to an other // OS native Thread because we need the native Thread ID of this thread // so we can terminate the thread if it hangs (this may happen at least under // Windows XP when invoking the native method NtQueryObject...). Thread.BeginThreadAffinity(); IntPtr processHandle = NativeMethods.GetCurrentProcess(); IntPtr threadHandle = NativeMethods.GetCurrentThread(); if (NativeMethods.DuplicateHandle(processHandle, threadHandle, processHandle, out this.nativeThreadId, 0, false, DuplicateHandleOptions.SameAccess)) { Logger.Log(LogLevel.Debug, "Getting the filename for handle " + this.Handle.ToInt32() + " in thread " + this.nativeThreadId.DangerousGetHandle()); } else { Logger.Log(LogLevel.Debug, "Getting the filename for handle " + this.Handle.ToInt32() + " in unknown thread"); } string fileName; bool retValue = GetFileNameFromHandle(this.Handle, out fileName); this.FileName = fileName; this.RetValue = retValue; }
private void ThreadBody(object parameter) { try { Thread.BeginThreadAffinity(); if (ProcessorAffinity != 0) { CurrentThread.ProcessorAffinity = new IntPtr(ProcessorAffinity); } if (_threadStart != null) { _threadStart(); } else if (_parameterizedThreadStart != null) { _parameterizedThreadStart(parameter); } else { throw new InvalidOperationException("Thread callback must be set first"); } } finally { CurrentThread.ProcessorAffinity = new IntPtr(0xFFFF); Thread.EndThreadAffinity(); } }
/// <summary> /// Define CPU affinity for current thread using OS's threading /// capabilities. This may not work on all platforms. /// </summary> /// <param name="cpus">[in] list of integers that maps to a CPU number /// </param> static protected void SetThreadProcessorAffinity(params int[] cpus) { if (cpus == null) { throw new ArgumentNullException("cpus"); } if (cpus.Length == 0) { throw new ArgumentException("You must specify at least one CPU.", "cpus"); } // Supports up to 64 processors. Build up CPU bitmask long cpuMask = 0; foreach (int cpu in cpus) { if (cpu < 0 || cpu >= ProcessorCount) { throw new ArgumentException("Invalid CPU number."); } cpuMask |= 1L << cpu; } // Ensure managed thread is linked to OS thread; does nothing on // default host in current .Net versions Thread.BeginThreadAffinity(); // Find the ProcessThread for this thread. ProcessThread thread = Process.GetCurrentProcess().Threads.Cast <ProcessThread>() .Where(t => t.Id == GetCurrentThreadId()).Single(); // Set the thread's processor affinity thread.ProcessorAffinity = (IntPtr)cpuMask; }
private void DistributedThreadStart(object parameter) { try { // fix to OS thread Thread.BeginThreadAffinity(); // set affinity if (ProcessorAffinity != 0) { CurrentThread.ProcessorAffinity = new IntPtr(ProcessorAffinity); } // call real thread if (this.threadStart != null) { this.threadStart(); } else if (this.parameterizedThreadStart != null) { this.parameterizedThreadStart(parameter); } else { throw new InvalidOperationException(); } } finally { // reset affinity CurrentThread.ProcessorAffinity = new IntPtr(0xFFFF); Thread.EndThreadAffinity(); } }
static void Main(string[] args) { uint threadId = 0; using (var threadStarted = new AutoResetEvent(false)) { var thread = new Thread(() => { try { Thread.BeginThreadAffinity(); threadId = GetCurrentThreadId(); threadStarted.Set(); // will throws System.OperationCanceledException Console.ReadLine(); } finally { Thread.EndThreadAffinity(); } }); thread.Start(); threadStarted.WaitOne(); } Debugger.Break(); CancelSynchronousIo(threadId); }
/// <summary> /// Parameterized constructor. /// </summary> /// <param name="saveAllChangesAtEndOfScope"> /// A boolean value that indicates whether to automatically save /// all object changes at end of the scope. /// </param> public UnitOfWorkScope(bool saveAllChangesAtEndOfScope, string connectionString) { if (_currentScope != null && !_currentScope._isDisposed) { throw new InvalidOperationException("ObjectContextScope instances cannot be nested."); } _giornale.Debug("+Apro Unit-Of-Work"); _saveAllChangesAtEndOfScope = saveAllChangesAtEndOfScope; /* Create a new ObjectContext instance: uso il proxy */ if (String.IsNullOrEmpty(connectionString)) { _dbContext = new LumenEntities(); } else { _dbContext = new LumenEntities(connectionString); } // _dbContext.Configuration.ProxyCreationEnabled = false; _isDisposed = false; Thread.BeginThreadAffinity(); /* Set the current scope to this UnitOfWorkScope object: */ _currentScope = this; }
/// <summary> /// Begins a new streaming scope letting commands with datareaders know to stream results instead of buffer. /// </summary> /// <exception cref="SecurityException">The caller does not have the required permission.</exception> #if !DOTNETCORE public StreamingScope(bool requireThreadAffinity = true) { _requireThreadAffinity = requireThreadAffinity; if (_requireThreadAffinity) { Thread.BeginThreadAffinity(); }
internal JsConfigScope() { #if !SILVERLIGHT Thread.BeginThreadAffinity(); #endif parent = head; head = this; }
internal JsonConfigScope() { #if !SILVERLIGHT Thread.BeginThreadAffinity(); #endif previous = current; current = this; }
public static void SetThreadProcessorAffinity(UIntPtr affinity) { Thread.BeginThreadAffinity(); IntPtr hThread = Native.GetCurrentThread(); Native.SetThreadAffinityMask(hThread, affinity); }
/// <summary> /// Starts thread processing. /// </summary> private void Start() { Log.Debug(".Run - timer thread starting"); long lTickAlign = _tickAlign; long lTickPeriod = _tickPeriod; try { Thread.BeginThreadAffinity(); while (_alive) { // Check the tickAlign to determine if we are here "too early" // The CLR is a little sloppy in the way that thread timers are handled. // In Java, when a timer is setup, the timer will adjust the interval // up and down to match the interval set by the requester. As a result, // you will can easily see intervals between calls that look like 109ms, // 94ms, 109ms, 94ms. This is how the JVM ensures that the caller gets // an average of 100ms. The CLR however will provide you with 109ms, // 109ms, 109ms, 109ms. Eventually this leads to slip in the timer. // To account for that we under allocate the timer interval by some // small amount and allow the thread to sleep a wee-bit if the timer // is too early to the next clock cycle. long currTickCount = DateTime.Now.Ticks; long currDelta = lTickAlign - currTickCount; //Log.Info("Curr: {0} {1} {2}", currDelta, currTickCount, Environment.TickCount); while (currDelta > INTERNAL_CLOCK_SLIP) { if (currDelta >= 600000) { Thread.Sleep(1); // force-yield quanta } else { Thread.SpinWait(20); } currTickCount = DateTime.Now.Ticks; currDelta = lTickAlign - currTickCount; //Log.Info("Curr: {0} {1} {2}", currDelta, currTickCount, Environment.TickCount); } lTickAlign += lTickPeriod; _timerCallback(null); } } catch (ThreadInterruptedException) { Thread.EndThreadAffinity(); } Log.Debug(".Run - timer thread stopping"); }
public void NotifyServiceStatusChangeTest() { var cnt = 0; ManualResetEvent evt; Thread.BeginThreadAffinity(); try { PFN_SC_NOTIFY_CALLBACK callback = ChangeDelegate; var svcNotify = new SERVICE_NOTIFY_2 { dwVersion = 2, pfnNotifyCallback = Marshal.GetFunctionPointerForDelegate(callback), }; using (evt = new ManualResetEvent(false)) using (var pNotify = new PinnedObject(svcNotify)) { Assert.That(NotifyServiceStatusChange(hSvc, SERVICE_NOTIFY_FLAGS.SERVICE_NOTIFY_PAUSED | SERVICE_NOTIFY_FLAGS.SERVICE_NOTIFY_PAUSE_PENDING | SERVICE_NOTIFY_FLAGS.SERVICE_NOTIFY_CONTINUE_PENDING, pNotify), ResultIs.Successful); var th = new Thread(ThreadExec); th.Start((SC_HANDLE)hSvc); while (!evt.WaitOne(5)) { ; } Assert.That(cnt, Is.GreaterThan(0)); } } finally { Thread.EndThreadAffinity(); } void ChangeDelegate(IntPtr pParameter) { System.Diagnostics.Debug.WriteLine(pParameter.ToStructure <SERVICE_NOTIFY_2>().ServiceStatus.dwCurrentState); cnt++; } void ThreadExec(object handle) { var svc = (SC_HANDLE)handle; System.Diagnostics.Debug.WriteLine("Pausing..."); if (!ControlService(svc, ServiceControl.SERVICE_CONTROL_PAUSE, out _)) { System.Diagnostics.Debug.WriteLine($"Pausing failed: {Win32Error.GetLastError()}"); } WaitForServiceStatus(svc, ServiceState.SERVICE_PAUSED); System.Diagnostics.Debug.WriteLine("Continuing..."); if (!ControlService(svc, ServiceControl.SERVICE_CONTROL_CONTINUE, out _)) { System.Diagnostics.Debug.WriteLine($"Pausing failed: {Win32Error.GetLastError()}"); } WaitForServiceStatus(svc, ServiceState.SERVICE_RUNNING); System.Diagnostics.Debug.WriteLine("Running..."); evt.Set(); } }