python threading multiprocessing module

The most basic multiprocessing example:

import threading
import time

def bar(start_time,sleep_time):
    print ('is start_time: ......',start_time)
    time.sleep(sleep_time)
    print ('sleep done,',sleep_time)

if __name__ == '__main__':
    b1 = threading.Thread(target=bar,args=(time.time(),44))
    b2 = threading.Thread(target=bar,args=(time.time(),65))
    b1.start()
    b2.start()

    print ('script done!')

 

join:

  Wait until the thread aborts. Blocks the calling thread until the thread's join() method is called to abort - exit normally or throw an unhandled exception - or an optional timeout occurs.

import threading
import time
def bar(name,sleep_time):
    print ('is start_time: ......',name)
    time.sleep(sleep_time)
    print ('sleep done,',sleep_time)
if __name__ == '__main__':
    b1 = threading.Thread(target=bar,args=('name_1',2))
    b2 = threading.Thread(target=bar,args=('name_2',3))

    b1.start()
    b2.start()
    b1.join()

    print ('script done!')

# is start_time: ...... name_1
# is start_time: ...... name_2
# sleep done, 2
# script done!
# sleep done, 3

 

setDaemon(daemonic) :

  Set the daemonic flag to boolean daemonic. It must be called before start() is called.

import threading
import time
def bar(name,sleep_time):
    print ('is start_time: ......',name)
    time.sleep(sleep_time)
    print ('sleep done,',name)
if __name__ == '__main__':
    threahs = list()

    b1 = threading.Thread(target=bar,args=('name_1',2))
    threahs.append(b1)
    b2 = threading.Thread(target=bar,args=('name_2',3))
    threahs.append(b2)

    b2.setDaemon(True)
    for i in threahs:
        i.start()

    print ('script done!')

# is start_time: ...... name_1
# is start_time: ...... name_2
# script done!
# sleep done, name_1

 

Here b2 is the daemon process, so it exits directly when the main process finishes running. I don't care whether the process of b2 is completed.

 

getName()
  returns the thread name.

setName(name)
  sets the thread name.
  The name is a string used for identification purposes only. It has no other effect. Multiple threads can have the same name. The initial name is set via the constructor.

isAlive()
  returns whether the thread is alive.

isDaemon()
  returns the thread's daemon thread flag

The run()
  method used to represent thread activity. You may override this method in a subclass of the Python Thread class. The standard run() method invokes the callback object passed as target to the object constructor.

 

test

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324810123&siteId=291194637