I am new to python and try to understand the concept of multi threading in python. As per my knowledge in Unix multi threading programming, if the main function is terminating, the threads created by main function will also get terminated irrespective of the work they are doing in the thread ( If we are not using any pthread_join() function).
But in while going through the multithreading in python , I am not seeing this feature. My threads are still running successfully even My main thread completing its work. So I want to know ,Threads in Python and Unix behave differently... or I am missing something. Please help in in understanding this thread feature in python. Here is the code in which is am using in python.
#! /usr/bin/python
import logging
import random
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class Counter(object):
def __init__(self, start=0):
self.lock = threading.Lock()
self.value = start
def increment(self):
logging.debug('Waiting for lock')
# Getting the Lock
self.lock.acquire()
try:
logging.debug('Acquired lock')
self.value = self.value + 1
finally:
# Releasing the Lock
self.lock.release()
def worker(c):
for i in range(2):
pause = 4
logging.debug('Sleeping for %0.02f', pause)
time.sleep(pause)
c.increment()
logging.debug('Done')
if __name__ == '__main__':
counter = Counter()
for i in range(2):
t = threading.Thread(target=worker, args=(counter,))
t.start()
logging.debug('Counter: %d', counter.value)