How to create a thread with a function to execute code in parallel with Python

2 Answers

0 votes
import threading
import time
 
def thread_function():
    for i in range(4):
        print('thread_function')
        time.sleep(2)
    print('END - thread_function()')
 
thrd = threading.Thread(target=thread_function)
 
thrd.start()
  
for i in range(4):
   print('python')
   time.sleep(1)
  
thrd.join()

print('END')
  
 
  
'''
run:
 
thread_function
python
python
thread_function
python
python
thread_function
thread_function
END - thread_function()
END
  
'''

 



answered Feb 4, 2020 by avibootz
edited Feb 4, 2020 by avibootz
0 votes
import threading
import time
 
def thread_function(s, n):
    print(s)    
    print(n)
    for i in range(4):
        print('thread_function')
        time.sleep(2)
    print('END - thread_function(s, n)')
 
thrd = threading.Thread(target=thread_function, args=('abc', 345))
 
thrd.start()
  
for i in range(4):
   print('python')
   time.sleep(1)
  
thrd.join()

print('END')

  
 
  
'''
run:
 
abc
python
345
thread_function
python
python
thread_function
python
thread_function
thread_function
END - thread_function(s, n)
END
  
'''

 



answered Feb 4, 2020 by avibootz
edited Feb 4, 2020 by avibootz

Related questions

1 answer 167 views
1 answer 281 views
281 views asked Dec 11, 2018 by avibootz
1 answer 256 views
1 answer 143 views
143 views asked Sep 28, 2019 by avibootz
2 answers 207 views
...