0

I have a function that takes multiple arguments (* args) of the string type. How every received argument is handled by a thread. Here's how I handled it:

def functionA(x):
    print(x)

def functionB(*args):
    for ar in args:
        th = threading.Thread(target=functionA, args=(ar, ))
        th.start()

But it doesn't work. Help me.

3
  • 1
    What you mean by but it doesn't work ? ... your code works fine. Commented Nov 22, 2020 at 11:41
  • @MauriceMeyer Yes. but it runs synchronously (in turn), not at the same time Commented Nov 22, 2020 at 14:39
  • It's working ^^. I got confused when writing run () and strart ().Thanks you Commented Nov 22, 2020 at 16:07

1 Answer 1

1

As mentioned in the comments your code works fine, adding some delay to functionA shows that all threads are started at the time:

import threading
import time
from datetime import datetime


def functionA(x, y):
    dte = datetime.utcnow()
    print(f"""Starting Thread {x:02} at: {dte:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(dte.microsecond // 1000)}""")
    time.sleep(y)
    print(x)
    dte = datetime.utcnow()
    print(f"""Stopping Thread {x:02} at: {dte:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(dte.microsecond // 1000)}""")

def functionB(*args):
    for i, ar in enumerate(args):
        th = threading.Thread(target=functionA, args=(ar, len(args)-i, ))
        th.start()


functionB(1,2,3,4,5,6,7,8,9,10)

Out:

Starting Thread 01 at: 2020-11-22 15:01:43.308
Starting Thread 02 at: 2020-11-22 15:01:43.308
Starting Thread 03 at: 2020-11-22 15:01:43.308
Starting Thread 04 at: 2020-11-22 15:01:43.308
Starting Thread 05 at: 2020-11-22 15:01:43.309
Starting Thread 06 at: 2020-11-22 15:01:43.309
Starting Thread 07 at: 2020-11-22 15:01:43.309
Starting Thread 08 at: 2020-11-22 15:01:43.309
Starting Thread 09 at: 2020-11-22 15:01:43.309
Starting Thread 10 at: 2020-11-22 15:01:43.309
10
Stopping Thread 10 at: 2020-11-22 15:01:44.310
9
Stopping Thread 09 at: 2020-11-22 15:01:45.311
8
Stopping Thread 08 at: 2020-11-22 15:01:46.309
7
Stopping Thread 07 at: 2020-11-22 15:01:47.314
6
Stopping Thread 06 at: 2020-11-22 15:01:48.311
5
Stopping Thread 05 at: 2020-11-22 15:01:49.310
4
Stopping Thread 04 at: 2020-11-22 15:01:50.310
3
Stopping Thread 03 at: 2020-11-22 15:01:51.311
2
Stopping Thread 02 at: 2020-11-22 15:01:52.309
1
Stopping Thread 01 at: 2020-11-22 15:01:53.311
Sign up to request clarification or add additional context in comments.

1 Comment

It's working ^^. I got confused when writing run () and strart ().Thanks you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.