#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/08/13 20:29:30 +0900> """ Python + Mutex sample. Windows only. by using ctypes. Windows10 x64 21H2 + Python 3.9.13 64bit """ import ctypes import time MUTEXNAME = "python_mutex_sample_02" def main(): knl32 = ctypes.windll.Kernel32 mtx = knl32.CreateMutexA(0, 1, MUTEXNAME) result = knl32.WaitForSingleObject(mtx, 0) if result != 0: print("%s already exists" % MUTEXNAME) else: print("New process.") for i in range(10): print(i) time.sleep(1) knl32.ReleaseMutex(mtx) knl32.CloseHandle(mtx) if __name__ == '__main__': main()