Python thread synchronization

Source: Internet
Author: User

from random import randintimport threadingfrom time import ctime,  sleepdata = [' A ',  ' B ',  ' C ',  ' d ',  ' e ',  ' f ',  ' g ',  ' h ',  ' I ',   ' J ']class mythread (threading. Thread):     lock = threading. Lock ()     def __init__ (self, task):         super (mythread, self). __init__ ()         self.task =  task    def run (self):         print ("in  time:{} Start Function:{}  ". Format (CTime (),  self.task.__name__)          self.lock.acquire ()         self.task ()         self.lock.release () Def a ():     # Modify the elements in the list from the back to the     for i in data[::-1]:        new_val =  ' xxx%s '  %  (Randint (100, 150))         index =  Data.index (i)         data[index] = new_val         print ("original value:{} with index:{} modified to:{}". Format (i, index, new_val)) def b ():     #从前往后依次读取列表      For i in data:        print ("Read Value:{}  index:{} ". Format (I, data.index (i))) Def main ():     funcs = [a, b]     threads = []    loop = range (Len (funcs))      for i in loop:        t =  MyThread (Funcs[i])  &NBSp;      threads.append (t)     for i in loop:         threads[i].start ()     for i in  loop:        threads[i].join () if __name__ ==  ' __ Main__ ':     main ()     print (" all done!!!")


Python thread synchronization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.