Reputation: 965
Maybe I just do not understand how Threading works entirely in Python, but to my understanding, the following code should be able to perform both loops simultaneously.
from threading import Thread
class minerThread(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def startMining(self,mineFunc):
while True:
print "geg"
def Main():
go=1
miner=minerThread()
miner.start()
miner.startMining("addr")
while go>0:
print "mine"
#Enter main loop
if(__name__ == "__main__"):
Main()
but instead, the program just hangs on the startMining
loop from the thread.
Does anyone know whats going on?
Upvotes: 2
Views: 2460
Reputation: 3203
CPython has something called GIL
(Global-Interpreter-Lock) which prevents 2 threads from executing simultenaously.
See: https://wiki.python.org/moin/GlobalInterpreterLock
In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)
Threads in Python are better suited for IO-bound tasks, where one thread blocks on input and allows other threads to execute.
What you try to do (in a very awkward way) is CPU bound and will only execute one thread at a time. There is switching amongst the threads at a determined amount of OpCodes. Buy your threads won't execute simultaneously.
If you want simultaneous execution, you should be looking at the multiprocessing
module
See: https://docs.python.org/3/library/multiprocessing.html
Note: In your threading code, you are executing the same code both from the main thread and the 2nd thread. Both are printing the same string, so it would difficult for you to recognize if the interpreter is switching amongst threads
Upvotes: 4