lowprio_windows.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package osutil
  7. import (
  8. "syscall"
  9. "github.com/pkg/errors"
  10. )
  11. var (
  12. kernel32, _ = syscall.LoadLibrary("kernel32.dll")
  13. setPriorityClass, _ = syscall.GetProcAddress(kernel32, "SetPriorityClass")
  14. )
  15. const (
  16. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx
  17. aboveNormalPriorityClass = 0x00008000
  18. belowNormalPriorityClass = 0x00004000
  19. highPriorityClass = 0x00000080
  20. idlePriorityClass = 0x00000040
  21. normalPriorityClass = 0x00000020
  22. processModeBackgroundBegin = 0x00100000
  23. processModeBackgroundEnd = 0x00200000
  24. realtimePriorityClass = 0x00000100
  25. )
  26. // SetLowPriority lowers the process CPU scheduling priority, and possibly
  27. // I/O priority depending on the platform and OS.
  28. func SetLowPriority() error {
  29. handle, err := syscall.GetCurrentProcess()
  30. if err != nil {
  31. return errors.Wrap(err, "get process handler")
  32. }
  33. defer syscall.CloseHandle(handle)
  34. res, _, err := syscall.Syscall(uintptr(setPriorityClass), uintptr(handle), belowNormalPriorityClass, 0, 0)
  35. if res != 0 {
  36. // "If the function succeeds, the return value is nonzero."
  37. return nil
  38. }
  39. return errors.Wrap(err, "set priority class") // wraps nil as nil
  40. }