Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

multiprocessing cannot send an object that holds a thread lock

Your error

TypeError: cannot pickle '_thread.RLock' object2 more lines it can show

Fix it fast

Most common cause, 1 of 3

A Process or Pool argument holds a lock under spawn or forkserver

Pass only plain values such as a URL, a path or a dict, and create the client inside each worker, for example in a Pool initializer that runs once per process.

Fix
import multiprocessing as mp

_client = None

def init_worker(api_url):
    global _client
    _client = make_client(api_url)   # built in the child, never pickled

def handle(item):
    return _client.send(item)

if __name__ == "__main__":
    with mp.Pool(4, initializer=init_worker, initargs=("https://api.example.com",)) as pool:
        print(pool.map(handle, range(10)))
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

TypeError: cannot pickle '_thread.RLock' object means multiprocessing had to pickle something that holds a lock: an API client, a handler or your own class. Under spawn and forkserver every Process argument is pickled, and every Queue item always is. Python 3.14 made forkserver the default on Linux. Send plain data and build the object inside the worker.

  • Applies to Python 3.15.2 and 3.14.6 (forkserver on Linux, spawn on macOS and Windows), Python 3.12.13 (fork on Linux)
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Print the start method, then try to pickle the object you send to the worker yourself. On Python 3.14 and later the error carries notes that name the attribute and the class holding the lock. An error at Process.start() or pool.map() means cause 1; a traceback from the queue's feeder thread means cause 2.

Run this first
python -c "import multiprocessing as mp; print(mp.get_start_method())"
python -c "import pickle, myapp; pickle.dumps(myapp.build_client())"

Then find the line you see in this list and open its fix:

  1. 1A Process or Pool argument holds a lock under spawn or forkserverThe traceback ends in Process.start(), Pool.map() or ProcessPoolExecutor.submit(), and the same code ran on Linux with Python 3.13 or older
  2. 2An object with a lock is put on a multiprocessing.QueueA traceback from multiprocessing/queues.py in _feed is printed, the put() call itself does not raise, and the consumer waits forever
  3. 3Your own class keeps a lock as an attributeThe Python 3.14 notes end with lines such as when serializing Client state and when serializing Client object, naming one of your classes

What does the error look like?

  • TypeError: cannot pickle '_thread.RLock' object
  • TypeError: can't pickle _thread.RLock objects
  • when serializing dict item 'lock'

Cause 1 of 3

A Process or Pool argument holds a lock under spawn or forkserver

You seeThe traceback ends in Process.start(), Pool.map() or ProcessPoolExecutor.submit(), and the same code ran on Linux with Python 3.13 or older

Check

cannot pickle '_thread.RLock' object at start-up means a target argument holds a lock and the start method has to pickle it. spawn is the default on Windows and macOS, and Python 3.14 replaced fork with forkserver on other Unix systems; both need picklable arguments. Under fork the child simply inherited the object, which is why old Linux code never complained.

Check
python -c "import multiprocessing as mp; print(mp.get_start_method())"

Fix

Pass only plain values such as a URL, a path or a dict, and create the client inside each worker, for example in a Pool initializer that runs once per process. Forcing the old behaviour with get_context("fork") still works on Linux, but the docs call fork threading-incompatible, so treat it as a stopgap.

Fix
import multiprocessing as mp

_client = None

def init_worker(api_url):
    global _client
    _client = make_client(api_url)   # built in the child, never pickled

def handle(item):
    return _client.send(item)

if __name__ == "__main__":
    with mp.Pool(4, initializer=init_worker, initargs=("https://api.example.com",)) as pool:
        print(pool.map(handle, range(10)))

Verify

The pool starts and returns results with the TypeError gone, under the platform's default start method.

Verify
python worker.py

Confirmed by docs.python.org

Did this fix it?

Cause 2 of 3

An object with a lock is put on a multiprocessing.Queue

You seeA traceback from multiprocessing/queues.py in _feed is printed, the put() call itself does not raise, and the consumer waits forever

Check

Queue.put() returns at once and a background feeder thread pickles the item later, whatever the start method. In CPython's queues.py, a pickling failure there prints the traceback and drops the item as if it had been silently removed, so the reader never receives it. Any object holding an RLock fails at this point.

Check
grep -n "\.put(" worker.py

Fix

Put plain data on the queue: tuples, dicts, strings or numbers that describe the work. Let the consumer turn that data back into rich objects on its own side.

Fix
# before: queue.put(order)            # order holds a client with a lock
queue.put({"order_id": order.id, "total": order.total})

Verify

The consumer receives every item, and no traceback from the feeder thread appears.

Verify
python producer_consumer.py

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 3

Your own class keeps a lock as an attribute

You seeThe Python 3.14 notes end with lines such as when serializing Client state and when serializing Client object, naming one of your classes

Check

When the lock lives inside a class you wrote and the instance must cross the process boundary, pickle copies the instance __dict__ and stops at the lock. The pickle docs show the pattern for this: __getstate__ returns a copy of the state without the unpicklable entry, and __setstate__ rebuilds it after loading.

Check
python -c "import pickle, myapp; pickle.dumps(myapp.Client())"

Fix

Leave the lock out of the pickled state and create a fresh one when the object is loaded in the child. Each process then gets its own lock, which is what a thread lock can protect anyway.

Fix
import threading

class Client:
    def __init__(self, url):
        self.url = url
        self.lock = threading.RLock()

    def __getstate__(self):
        state = self.__dict__.copy()
        del state["lock"]
        return state

    def __setstate__(self, state):
        self.__dict__.update(state)
        self.lock = threading.RLock()

Verify

pickle.dumps(Client(...)) returns bytes, and pickle.loads() gives back an object with a working lock.

Verify
python -c "import pickle, myapp; c = pickle.loads(pickle.dumps(myapp.Client('x'))); print(c.url, c.lock)"

Confirmed by docs.python.org

Did this fix it?

How do I stop it coming back?

  • Run the test suite once with multiprocessing.set_start_method("spawn") so a Linux CI job catches unpicklable arguments before macOS or Windows users do.
  • Give worker functions only primitive arguments, and create connections, clients and loggers inside the child process.
  • Wrap pickle.dumps() around every new message type in a unit test before it is sent through a Queue.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.