Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use an inline function in a Thread call?

The documentation for threading.Thread(target=...) states that

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

I usually use it like this:

import threading

def worker():
    a = 3
    print("bonjour {a}".format(a=a))

threading.Thread(target=worker).start()

Is there a way to chain the function elements in target so that a new one does not need to be defined? Something like (pseudocode obviously)

threading.Thread(target=(a=3;print("bonjour {a}".format(a=a))).start()

I have a bunch of very short calls to make in the Thread call and would like to avoid multiplication of function definitions.

like image 851
WoJ Avatar asked Feb 06 '16 18:02

WoJ


People also ask

Can a Thread call a function?

Yes, but you should take care that the function does not alter state in such a way that other threads would be impacted negatively.

What is inline Thread?

I believe it refers to the practice of creating an anonymous class extending Thread and calling its start method in the same line of code.

What is inline function calls?

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.

Can two threads call the same function?

There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.


2 Answers

You can use a lambda function in Python 3.x

import threading

threading.Thread(target=lambda a: print("Hello, {}".format(a)), args=(["world"]))

You should probably take a look at this SO question to see why you can't use print in Python 2.x in lambda expressions.


Actually, you can fit many function calls into your lambda:

from __future__ import print_function # I'm on Python 2.7
from threading import Thread

Thread(target=(lambda: print('test') == print('hello'))).start()

That will print both test and hello.

like image 141
ForceBru Avatar answered Oct 01 '22 19:10

ForceBru


I don't really like using exec, but in Python3.x it is a function, so you could do

threading.Thread(target=exec, args=('a=3; print("bonjour {a}".format(a=a))',)
like image 29
zondo Avatar answered Oct 01 '22 21:10

zondo