Вот есть два примера, с одинаковой логикой , но написанных через разные модули.
Так вот на основе модуля threading сценарий выполняется моментально, а на основе модуля _thread около двух секунд. Помогите разобраться почему?
На основе threading:
import threading class MyThread(threading.Thread): def __init__(self, myid, count, mutex): self.myid = myid self.count = count self.mutex = mutex threading.Thread.__init__(self) def run(self): for i in range(self.count): with self.mutex: print('[{}] => {}'.format(self.myid, i)) stdoutmutex = threading.Lock() threads = [] for i in range(10): thread = MyThread(i, 100, stdoutmutex) thread.start() threads.append(thread) for thread in threads: thread.join() print('MAIN EXITING')
На основе _thread:
import _thread stdoutmutex = _thread.allocate_lock() exitmutexes = [_thread.allocate_lock() for i in range(10)] def counter(myId, count): for i in range(count): stdoutmutex.acquire() print('[{}] => {}'.format(myId, i)) stdoutmutex.release() exitmutexes[myId].acquire() for i in range(10): _thread.start_new_thread(counter, (i, 100)) for mutex in exitmutexes: while not mutex.locked(): pass print('main thread exiting')