| 1 |
|
| 2 |
============================= |
| 3 |
Software Transactional Memory |
| 4 |
============================= |
| 5 |
|
| 6 |
.. contents:: |
| 7 |
|
| 8 |
**Warning:** The below is relatively out of date, the ``pypy-stm``-variant is |
| 9 |
no longer actively being developed. For a description of the technical details |
| 10 |
as well as the pros and cons of the approach, you can read the 2019 `paper`__ |
| 11 |
by Remi Meier and also his `PhD thesis`__. |
| 12 |
|
| 13 |
.. __: https://dl.acm.org/doi/abs/10.1145/3359619.3359747 |
| 14 |
.. __: https://www.research-collection.ethz.ch/handle/20.500.11850/371019 |
| 15 |
|
| 16 |
This page is about ``pypy-stm``, a special in-development version of |
| 17 |
PyPy which can run multiple independent CPU-hungry threads in the same |
| 18 |
process in parallel. It is a solution to what is known in the Python |
| 19 |
world as the "global interpreter lock (GIL)" problem --- it is an |
| 20 |
implementation of Python without the GIL. |
| 21 |
|
| 22 |
"STM" stands for Software `Transactional Memory`_, the technique used |
| 23 |
internally. This page describes ``pypy-stm`` from the perspective of a |
| 24 |
user, describes work in progress, and finally gives references to more |
| 25 |
implementation details. |
| 26 |
|
| 27 |
This work was done by Remi Meier and Armin Rigo. Thanks to all donors |
| 28 |
for crowd-funding the work so far! Please have a look at the `2nd call |
| 29 |
for donation`_. |
| 30 |
|
| 31 |
.. _`Transactional Memory`: https://en.wikipedia.org/wiki/Transactional_memory |
| 32 |
.. _`2nd call for donation`: https://pypy.org/tmdonate2.html |
| 33 |
|
| 34 |
|
| 35 |
What pypy-stm is for |
| 36 |
==================== |
| 37 |
|
| 38 |
``pypy-stm`` is a variant of the regular PyPy interpreter. (This |
| 39 |
version supports Python 2.7; see below for `Python 3, CPython, |
| 40 |
and others`_.) With caveats_ |
| 41 |
listed below, it should be in theory within 20%-50% slower than a |
| 42 |
regular PyPy, comparing the JIT version in both cases (but see below!). |
| 43 |
It is called |
| 44 |
STM for Software Transactional Memory, which is the internal technique |
| 45 |
used (see `Reference to implementation details`_). |
| 46 |
|
| 47 |
The benefit is that the resulting ``pypy-stm`` can execute multiple |
| 48 |
threads of Python code in parallel. Programs running two threads or |
| 49 |
more in parallel should ideally run faster than in a regular PyPy |
| 50 |
(either now, or soon as bugs are fixed). |
| 51 |
|
| 52 |
* ``pypy-stm`` is fully compatible with a GIL-based PyPy; you can use |
| 53 |
it as a drop-in replacement and multithreaded programs will run on |
| 54 |
multiple cores. |
| 55 |
|
| 56 |
* ``pypy-stm`` provides (but does not impose) a special API to the |
| 57 |
user in the pure Python module ``transaction``. This module is based |
| 58 |
on the lower-level module ``pypystm``, but also provides some |
| 59 |
compatibility with non-STM PyPy's or CPython's. |
| 60 |
|
| 61 |
* Building on top of the way the GIL is removed, we will talk |
| 62 |
about `How to write multithreaded programs: the 10'000-feet view`_ |
| 63 |
and `transaction.TransactionQueue`_. |
| 64 |
|
| 65 |
|
| 66 |
...and what pypy-stm is not for |
| 67 |
------------------------------- |
| 68 |
|
| 69 |
``pypy-stm`` gives a Python without the GIL. This means that it is |
| 70 |
useful in situations where the GIL is the problem in the first place. |
| 71 |
(This includes cases where the program can easily be modified to run |
| 72 |
in multiple threads; often, we don't consider doing that precisely |
| 73 |
because of the GIL.) |
| 74 |
|
| 75 |
However, there are plenty of cases where the GIL is not the problem. |
| 76 |
Do not hope ``pypy-stm`` to be helpful in these cases! This includes |
| 77 |
all programs that use multiple threads but don't actually spend a lot |
| 78 |
of time running Python code. For example, it may be spending all its |
| 79 |
time waiting for I/O to occur, or performing some long computation on |
| 80 |
a huge matrix. These are cases where the CPU is either idle, or in |
| 81 |
some C/Fortran library anyway; in both cases, the interpreter (either |
| 82 |
CPython or the regular PyPy) should release the GIL around the |
| 83 |
external calls. The threads will thus not end up fighting for the |
| 84 |
GIL. |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
Getting Started |
| 89 |
=============== |
| 90 |
|
| 91 |
**pypy-stm requires 64-bit Linux for now.** |
| 92 |
|
| 93 |
Development is done in the branch `stmgc-c8`_. If you are only |
| 94 |
interested in trying it out, please pester us until we upload a recent |
| 95 |
prebuilt binary. The current version supports four "segments", which |
| 96 |
means that it will run up to four threads in parallel. |
| 97 |
|
| 98 |
To build a version from sources, you first need to compile a custom |
| 99 |
version of gcc(!). See the instructions here: |
| 100 |
https://bitbucket.org/pypy/stmgc/src/default/gcc-seg-gs/ |
| 101 |
(Note that these patches are being incorporated into gcc. It is likely |
| 102 |
that future versions of gcc will not need to be patched any more.) |
| 103 |
|
| 104 |
Then get the branch `stmgc-c8`_ of PyPy and run:: |
| 105 |
|
| 106 |
cd pypy/goal |
| 107 |
../../rpython/bin/rpython -Ojit --stm |
| 108 |
|
| 109 |
At the end, this will try to compile the generated C code by calling |
| 110 |
``gcc-seg-gs``, which must be the script you installed in the |
| 111 |
instructions above. |
| 112 |
|
| 113 |
.. _`stmgc-c8`: https://bitbucket.org/pypy/pypy/src/stmgc-c8/ |
| 114 |
|
| 115 |
|
| 116 |
.. _caveats: |
| 117 |
|
| 118 |
Current status (stmgc-c7) |
| 119 |
------------------------- |
| 120 |
|
| 121 |
.. warning:: |
| 122 |
|
| 123 |
THIS PAGE IS OLD, THE REST IS ABOUT STMGC-C7 WHEREAS THE CURRENT |
| 124 |
DEVELOPMENT WORK IS DONE ON STMGC-C8 |
| 125 |
|
| 126 |
|
| 127 |
* **NEW:** It seems to work fine, without crashing any more. Please `report |
| 128 |
any crash`_ you find (or other bugs). |
| 129 |
|
| 130 |
* It runs with an overhead as low as 20% on examples like "richards". |
| 131 |
There are also other examples with higher overheads --currently up to |
| 132 |
2x for "translate.py"-- which we are still trying to understand. |
| 133 |
One suspect is our partial GC implementation, see below. |
| 134 |
|
| 135 |
* **NEW:** the ``PYPYSTM`` environment variable and the |
| 136 |
``pypy/stm/print_stm_log.py`` script let you know exactly which |
| 137 |
"conflicts" occurred. This is described in the section |
| 138 |
`transaction.TransactionQueue`_ below. |
| 139 |
|
| 140 |
* **NEW:** special transaction-friendly APIs (like ``stmdict``), |
| 141 |
described in the section `transaction.TransactionQueue`_ below. The |
| 142 |
old API changed again, mostly moving to different modules. Sorry |
| 143 |
about that. I feel it's a better idea to change the API early |
| 144 |
instead of being stuck with a bad one later... |
| 145 |
|
| 146 |
* Currently limited to 1.5 GB of RAM (this is just a parameter in |
| 147 |
`core.h`__ -- theoretically. In practice, increase it too much and |
| 148 |
clang crashes again). Memory overflows are not correctly handled; |
| 149 |
they cause segfaults. |
| 150 |
|
| 151 |
* **NEW:** The JIT warm-up time improved again, but is still |
| 152 |
relatively large. In order to produce machine code, the JIT needs |
| 153 |
to enter "inevitable" mode. This means that you will get bad |
| 154 |
performance results if your program doesn't run for several seconds, |
| 155 |
where *several* can mean *many.* When trying benchmarks, be sure to |
| 156 |
check that you have reached the warmed state, i.e. the performance |
| 157 |
is not improving any more. |
| 158 |
|
| 159 |
* The GC is new; although clearly inspired by PyPy's regular GC, it |
| 160 |
misses a number of optimizations for now. Programs allocating large |
| 161 |
numbers of small objects that don't immediately die (surely a common |
| 162 |
situation) suffer from these missing optimizations. (The bleeding |
| 163 |
edge ``stmgc-c8`` is better at that.) |
| 164 |
|
| 165 |
* Weakrefs might appear to work a bit strangely for now, sometimes |
| 166 |
staying alive through ``gc.collect()``, or even dying but then |
| 167 |
un-dying for a short time before dying again. A similar problem can |
| 168 |
show up occasionally elsewhere with accesses to some external |
| 169 |
resources, where the (apparent) serialized order doesn't match the |
| 170 |
underlying (multithreading) order. These are bugs (partially fixed |
| 171 |
already in ``stmgc-c8``). Also, debugging helpers like |
| 172 |
``weakref.getweakrefcount()`` might give wrong answers. |
| 173 |
|
| 174 |
* The STM system is based on very efficient read/write barriers, which |
| 175 |
are mostly done (their placement could be improved a bit in |
| 176 |
JIT-generated machine code). |
| 177 |
|
| 178 |
* Forking the process is slow because the complete memory needs to be |
| 179 |
copied manually. A warning is printed to this effect. |
| 180 |
|
| 181 |
* Very long-running processes (on the order of days) will eventually |
| 182 |
crash on an assertion error because of a non-implemented overflow of |
| 183 |
an internal 28-bit counter. |
| 184 |
|
| 185 |
* The recursion detection code was not reimplemented. Infinite |
| 186 |
recursion just segfaults for now. |
| 187 |
|
| 188 |
|
| 189 |
.. _`report any crash`: https://bitbucket.org/pypy/pypy/issues?status=new&status=open |
| 190 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/src_stm/stm/core.h |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
Python 3, CPython, and others |
| 195 |
============================= |
| 196 |
|
| 197 |
In this document I describe "pypy-stm", which is based on PyPy's Python |
| 198 |
2.7 interpreter. Supporting Python 3 should take about half an |
| 199 |
afternoon of work. Obviously, what I *don't* mean is that by tomorrow |
| 200 |
you can have a finished and polished "pypy3-stm" product. General py3k |
| 201 |
work is still missing; and general stm work is also still missing. But |
| 202 |
they are rather independent from each other, as usual in PyPy. The |
| 203 |
required afternoon of work will certainly be done one of these days now |
| 204 |
that the internal interfaces seem to stabilize. |
| 205 |
|
| 206 |
The same is true for other languages implemented in the RPython |
| 207 |
framework, although the amount of work to put there might vary, because |
| 208 |
the STM framework within RPython is currently targeting the PyPy |
| 209 |
interpreter and other ones might have slightly different needs. |
| 210 |
But in general, all the tedious transformations are done by RPython |
| 211 |
and you're only left with the (hopefully few) hard and interesting bits. |
| 212 |
|
| 213 |
The core of STM works as a library written in C (see `reference to |
| 214 |
implementation details`_ below). It means that it can be used on |
| 215 |
other interpreters than the ones produced by RPython. Duhton_ is an |
| 216 |
early example of that. At this point, you might think about adapting |
| 217 |
this library for CPython. You're warned, though: as far as I can |
| 218 |
tell, it is a doomed idea. I had a hard time debugging Duhton, and |
| 219 |
that's infinitely simpler than CPython. Even ignoring that, you can |
| 220 |
see in the C sources of Duhton that many core design decisions are |
| 221 |
different than in CPython: no refcounting; limited support for |
| 222 |
prebuilt "static" objects; ``stm_read()`` and ``stm_write()`` macro |
| 223 |
calls everywhere (and getting very rare and very obscure bugs if you |
| 224 |
forget one); and so on. You could imagine some custom special-purpose |
| 225 |
extension of the C language, which you would preprocess to regular C. |
| 226 |
In my opinion that's starting to look a lot like RPython itself, but |
| 227 |
maybe you'd prefer this approach. Of course you still have to worry |
| 228 |
about each and every C extension module you need, but maybe you'd have |
| 229 |
a way forward. |
| 230 |
|
| 231 |
.. _Duhton: https://bitbucket.org/pypy/duhton |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
User Guide |
| 236 |
========== |
| 237 |
|
| 238 |
How to write multithreaded programs: the 10'000-feet view |
| 239 |
--------------------------------------------------------- |
| 240 |
|
| 241 |
PyPy-STM offers two ways to write multithreaded programs: |
| 242 |
|
| 243 |
* the traditional way, using the ``thread`` or ``threading`` modules, |
| 244 |
described first__. |
| 245 |
|
| 246 |
* using ``TransactionQueue``, described next__, as a way to hide the |
| 247 |
low-level notion of threads. |
| 248 |
|
| 249 |
.. __: `Drop-in replacement`_ |
| 250 |
.. __: `transaction.TransactionQueue`_ |
| 251 |
|
| 252 |
The issues with low-level threads are well known (particularly in other |
| 253 |
languages that don't have GIL-based interpreters): memory corruption, |
| 254 |
deadlocks, livelocks, and so on. There are alternative approaches to |
| 255 |
dealing directly with threads, like OpenMP_. These approaches |
| 256 |
typically enforce some structure on your code. ``TransactionQueue`` |
| 257 |
is in part similar: your program needs to have "some chances" of |
| 258 |
parallelization before you can apply it. But I believe that the scope |
| 259 |
of applicability is much larger with ``TransactionQueue`` than with |
| 260 |
other approaches. It usually works without forcing a complete |
| 261 |
reorganization of your existing code, and it works on any Python |
| 262 |
program which has got *latent* and *imperfect* parallelism. Ideally, |
| 263 |
it only requires that the end programmer identifies where this |
| 264 |
parallelism is likely to be found, and communicates it to the system |
| 265 |
using a simple API. |
| 266 |
|
| 267 |
.. _OpenMP: https://en.wikipedia.org/wiki/OpenMP |
| 268 |
|
| 269 |
|
| 270 |
Drop-in replacement |
| 271 |
------------------- |
| 272 |
|
| 273 |
Multithreaded, CPU-intensive Python programs should work unchanged on |
| 274 |
``pypy-stm``. They will run using multiple CPU cores in parallel. |
| 275 |
|
| 276 |
The existing semantics of the GIL (Global Interpreter Lock) are |
| 277 |
unchanged: although running on multiple cores in parallel, ``pypy-stm`` |
| 278 |
gives the illusion that threads are run serially, with switches only |
| 279 |
occurring between bytecodes, not in the middle of them. Programs can |
| 280 |
rely on this: using ``shared_list.append()/pop()`` or |
| 281 |
``shared_dict.setdefault()`` as synchronization mechanisms continues to |
| 282 |
work as expected. |
| 283 |
|
| 284 |
This works by internally considering the points where a standard PyPy or |
| 285 |
CPython would release the GIL, and replacing them with the boundaries of |
| 286 |
"transactions". Like their database equivalent, multiple transactions |
| 287 |
can execute in parallel, but will commit in some serial order. They |
| 288 |
appear to behave as if they were completely run in this serialization |
| 289 |
order. |
| 290 |
|
| 291 |
|
| 292 |
transaction.TransactionQueue |
| 293 |
---------------------------- |
| 294 |
|
| 295 |
In CPU-hungry programs, we can often easily identify outermost loops |
| 296 |
over some data structure, or other repetitive algorithm, where each |
| 297 |
"block" consists of processing a non-trivial amount of data, and where |
| 298 |
the blocks "have a good chance" to be independent from each other. We |
| 299 |
don't need to prove that they are actually independent: it is enough |
| 300 |
if they are *often independent* --- or, more precisely, if we *think |
| 301 |
they should be* often independent. |
| 302 |
|
| 303 |
One typical example would look like this, where the function ``func()`` |
| 304 |
typically invokes a large amount of code:: |
| 305 |
|
| 306 |
for key, value in bigdict.items(): |
| 307 |
func(key, value) |
| 308 |
|
| 309 |
Then you simply replace the loop with:: |
| 310 |
|
| 311 |
from transaction import TransactionQueue |
| 312 |
|
| 313 |
tr = TransactionQueue() |
| 314 |
for key, value in bigdict.items(): |
| 315 |
tr.add(func, key, value) |
| 316 |
tr.run() |
| 317 |
|
| 318 |
This code's behavior is equivalent. Internally, the |
| 319 |
``TransactionQueue`` object will start N threads and try to run the |
| 320 |
``func(key, value)`` calls on all threads in parallel. But note the |
| 321 |
difference with a regular thread-pooling library, as found in many |
| 322 |
lower-level languages than Python: the function calls are not randomly |
| 323 |
interleaved with each other just because they run in parallel. The |
| 324 |
behavior did not change because we are using ``TransactionQueue``. |
| 325 |
All the calls still *appear* to execute in some serial order. |
| 326 |
|
| 327 |
A typical usage of ``TransactionQueue`` goes like that: at first, |
| 328 |
the performance does not increase. |
| 329 |
In fact, it is likely to be worse. Typically, this is |
| 330 |
indicated by the total CPU usage, which remains low (closer to 1 than |
| 331 |
N cores). First note that it is expected that the CPU usage should |
| 332 |
not go much higher than 1 in the JIT warm-up phase: you must run a |
| 333 |
program for several seconds, or for larger programs at least one |
| 334 |
minute, to give the JIT a chance to warm up enough. But if CPU usage |
| 335 |
remains low even afterwards, then the ``PYPYSTM`` environment variable |
| 336 |
can be used to track what is going on. |
| 337 |
|
| 338 |
Run your program with ``PYPYSTM=logfile`` to produce a log file called |
| 339 |
``logfile``. Afterwards, use the ``pypy/stm/print_stm_log.py`` |
| 340 |
utility to inspect the content of this log file. It produces output |
| 341 |
like this (sorted by amount of time lost, largest first):: |
| 342 |
|
| 343 |
10.5s lost in aborts, 1.25s paused (12412x STM_CONTENTION_WRITE_WRITE) |
| 344 |
File "foo.py", line 10, in f |
| 345 |
someobj.stuff = 5 |
| 346 |
File "bar.py", line 20, in g |
| 347 |
someobj.other = 10 |
| 348 |
|
| 349 |
This means that 10.5 seconds were lost running transactions that were |
| 350 |
aborted (which caused another 1.25 seconds of lost time by pausing), |
| 351 |
because of the reason shown in the two independent single-entry |
| 352 |
tracebacks: one thread ran the line ``someobj.stuff = 5``, whereas |
| 353 |
another thread concurrently ran the line ``someobj.other = 10`` on the |
| 354 |
same object. These two writes are done to the same object. This |
| 355 |
causes a conflict, which aborts one of the two transactions. In the |
| 356 |
example above this occurred 12412 times. |
| 357 |
|
| 358 |
The two other conflict sources are ``STM_CONTENTION_INEVITABLE``, |
| 359 |
which means that two transactions both tried to do an external |
| 360 |
operation, like printing or reading from a socket or accessing an |
| 361 |
external array of raw data; and ``STM_CONTENTION_WRITE_READ``, which |
| 362 |
means that one transaction wrote to an object but the other one merely |
| 363 |
read it, not wrote to it (in that case only the writing transaction is |
| 364 |
reported; the location for the reads is not recorded because doing so |
| 365 |
is not possible without a very large performance impact). |
| 366 |
|
| 367 |
Common causes of conflicts: |
| 368 |
|
| 369 |
* First of all, any I/O or raw manipulation of memory turns the |
| 370 |
transaction inevitable ("must not abort"). There can be only one |
| 371 |
inevitable transaction running at any time. A common case is if |
| 372 |
each transaction starts with sending data to a log file. You should |
| 373 |
refactor this case so that it occurs either near the end of the |
| 374 |
transaction (which can then mostly run in non-inevitable mode), or |
| 375 |
delegate it to a separate transaction or even a separate thread. |
| 376 |
|
| 377 |
* Writing to a list or a dictionary conflicts with any read from the |
| 378 |
same list or dictionary, even one done with a different key. For |
| 379 |
dictionaries and sets, you can try the types ``transaction.stmdict`` |
| 380 |
and ``transaction.stmset``, which behave mostly like ``dict`` and |
| 381 |
``set`` but allow concurrent access to different keys. (What is |
| 382 |
missing from them so far is lazy iteration: for example, |
| 383 |
``stmdict.iterkeys()`` is implemented as ``iter(stmdict.keys())``; |
| 384 |
and, unlike PyPy's dictionaries and sets, the STM versions are not |
| 385 |
ordered.) There are also experimental ``stmiddict`` and |
| 386 |
``stmidset`` classes using the identity of the key. |
| 387 |
|
| 388 |
* ``time.time()`` and ``time.clock()`` turn the transaction inevitable |
| 389 |
in order to guarantee that a call that appears to be later will really |
| 390 |
return a higher number. If getting slightly unordered results is |
| 391 |
fine, use ``transaction.time()`` or ``transaction.clock()``. The |
| 392 |
latter operations guarantee to return increasing results only if you |
| 393 |
can "prove" that two calls occurred in a specific order (for example |
| 394 |
because they are both called by the same thread). In cases where no |
| 395 |
such proof is possible, you might get randomly interleaved values. |
| 396 |
(If you have two independent transactions, they normally behave as if |
| 397 |
one of them was fully executed before the other; but using |
| 398 |
``transaction.time()`` you might see the "hidden truth" that they are |
| 399 |
actually interleaved.) |
| 400 |
|
| 401 |
* ``transaction.threadlocalproperty`` can be used at class-level:: |
| 402 |
|
| 403 |
class Foo(object): # must be a new-style class! |
| 404 |
x = transaction.threadlocalproperty() |
| 405 |
y = transaction.threadlocalproperty(dict) |
| 406 |
|
| 407 |
This declares that instances of ``Foo`` have two attributes ``x`` |
| 408 |
and ``y`` that are thread-local: reading or writing them from |
| 409 |
concurrently-running transactions will return independent results. |
| 410 |
(Any other attributes of ``Foo`` instances will be globally visible |
| 411 |
from all threads, as usual.) This is useful together with |
| 412 |
``TransactionQueue`` for these two cases: |
| 413 |
|
| 414 |
- For attributes of long-lived objects that change during one |
| 415 |
transaction, but should always be reset to some initial value |
| 416 |
around transaction (for example, initialized to 0 at the start of |
| 417 |
a transaction; or, if used for a list of pending things to do |
| 418 |
within this transaction, it will always be empty at the end of one |
| 419 |
transaction). |
| 420 |
|
| 421 |
- For general caches across transactions. With ``TransactionQueue`` |
| 422 |
you get a pool of a fixed number N of threads, each running the |
| 423 |
transactions serially. A thread-local property will have the |
| 424 |
value last stored in it by the same thread, which may come from a |
| 425 |
random previous transaction. Basically, you get N copies of the |
| 426 |
property's value, and each transaction accesses a random copy. It |
| 427 |
works fine for caches. |
| 428 |
|
| 429 |
In more details, the optional argument to ``threadlocalproperty()`` |
| 430 |
is the default value factory: in case no value was assigned in the |
| 431 |
current thread yet, the factory is called and its result becomes the |
| 432 |
value in that thread (like ``collections.defaultdict``). If no |
| 433 |
default value factory is specified, uninitialized reads raise |
| 434 |
``AttributeError``. |
| 435 |
|
| 436 |
* In addition to all of the above, there are cases where write-write |
| 437 |
conflicts are caused by writing the same value to an attribute again |
| 438 |
and again. See for example ea2e519614ab_: this fixes two such |
| 439 |
issues where we write an object field without first checking if we |
| 440 |
already did it. The ``dont_change_any_more`` field is a flag set to |
| 441 |
``True`` in that part of the code, but usually this |
| 442 |
``rtyper_makekey()`` method will be called many times for the same |
| 443 |
object; the code used to repeatedly set the flag to ``True``, but |
| 444 |
now it first checks and only does the write if it is ``False``. |
| 445 |
Similarly, in the second half of the check in, the method |
| 446 |
``setup_block_entry()`` used to both assign the ``concretetype`` |
| 447 |
fields and return a list, but its two callers were different: one |
| 448 |
would really need the ``concretetype`` fields initialized, whereas |
| 449 |
the other would only need to get its result list --- the |
| 450 |
``concretetype`` field in that case might already be set or not, but |
| 451 |
that would not matter. |
| 452 |
|
| 453 |
.. _ea2e519614ab: https://bitbucket.org/pypy/pypy/commits/ea2e519614ab |
| 454 |
|
| 455 |
Note that Python is a complicated language; there are a number of less |
| 456 |
common cases that may cause conflict (of any kind) where we might not |
| 457 |
expect it at priori. In many of these cases it could be fixed; please |
| 458 |
report any case that you don't understand. |
| 459 |
|
| 460 |
|
| 461 |
Atomic sections |
| 462 |
--------------- |
| 463 |
|
| 464 |
The ``TransactionQueue`` class described above is based on *atomic |
| 465 |
sections,* which are blocks of code which you want to execute without |
| 466 |
"releasing the GIL". In STM terms, this means blocks of code that are |
| 467 |
executed while guaranteeing that the transaction is not interrupted in |
| 468 |
the middle. *This is experimental and may be removed in the future* |
| 469 |
if `Software lock elision`_ is ever implemented. |
| 470 |
|
| 471 |
Here is a direct usage example:: |
| 472 |
|
| 473 |
with transaction.atomic: |
| 474 |
assert len(lst1) == 10 |
| 475 |
x = lst1.pop(0) |
| 476 |
lst1.append(x) |
| 477 |
|
| 478 |
In this example, we are sure that the item popped off one end of |
| 479 |
the list is appended again at the other end atomically. It means that |
| 480 |
another thread can run ``len(lst1)`` or ``x in lst1`` without any |
| 481 |
particular synchronization, and always see the same results, |
| 482 |
respectively ``10`` and ``True``. It will never see the intermediate |
| 483 |
state where ``lst1`` only contains 9 elements. Atomic sections are |
| 484 |
similar to re-entrant locks (they can be nested), but additionally they |
| 485 |
protect against the concurrent execution of *any* code instead of just |
| 486 |
code that happens to be protected by the same lock in other threads. |
| 487 |
|
| 488 |
Note that the notion of atomic sections is very strong. If you write |
| 489 |
code like this:: |
| 490 |
|
| 491 |
with __pypy__.thread.atomic: |
| 492 |
time.sleep(10) |
| 493 |
|
| 494 |
then, if you think about it as if we had a GIL, you are executing a |
| 495 |
10-seconds-long atomic transaction without releasing the GIL at all. |
| 496 |
This prevents all other threads from progressing at all. While it is |
| 497 |
not strictly true in ``pypy-stm``, the exact rules for when other |
| 498 |
threads can progress or not are rather complicated; you have to consider |
| 499 |
it likely that such a piece of code will eventually block all other |
| 500 |
threads anyway. |
| 501 |
|
| 502 |
Note that if you want to experiment with ``atomic``, you may have to |
| 503 |
manually add a transaction break just before the atomic block. This is |
| 504 |
because the boundaries of the block are not guaranteed to be the |
| 505 |
boundaries of the transaction: the latter is at least as big as the |
| 506 |
block, but may be bigger. Therefore, if you run a big atomic block, it |
| 507 |
is a good idea to break the transaction just before. This can be done |
| 508 |
by calling ``transaction.hint_commit_soon()``. (This may be fixed at |
| 509 |
some point.) |
| 510 |
|
| 511 |
There are also issues with the interaction of regular locks and atomic |
| 512 |
blocks. This can be seen if you write to files (which have locks), |
| 513 |
including with a ``print`` to standard output. If one thread tries to |
| 514 |
acquire a lock while running in an atomic block, and another thread |
| 515 |
has got the same lock at that point, then the former may fail with a |
| 516 |
``thread.error``. (Don't rely on it; it may also deadlock.) |
| 517 |
The reason is that "waiting" for some condition to |
| 518 |
become true --while running in an atomic block-- does not really make |
| 519 |
sense. For now you can work around it by making sure that, say, all |
| 520 |
your prints are either in an ``atomic`` block or none of them are. |
| 521 |
(This kind of issue is theoretically hard to solve and may be the |
| 522 |
reason for atomic block support to eventually be removed.) |
| 523 |
|
| 524 |
|
| 525 |
Locks |
| 526 |
----- |
| 527 |
|
| 528 |
**Not Implemented Yet** |
| 529 |
|
| 530 |
The thread module's locks have their basic semantic unchanged. However, |
| 531 |
using them (e.g. in ``with my_lock:`` blocks) starts an alternative |
| 532 |
running mode, called `Software lock elision`_. This means that PyPy |
| 533 |
will try to make sure that the transaction extends until the point where |
| 534 |
the lock is released, and if it succeeds, then the acquiring and |
| 535 |
releasing of the lock will be "elided". This means that in this case, |
| 536 |
the whole transaction will technically not cause any write into the lock |
| 537 |
object --- it was unacquired before, and is still unacquired after the |
| 538 |
transaction. |
| 539 |
|
| 540 |
This is specially useful if two threads run ``with my_lock:`` blocks |
| 541 |
with the same lock. If they each run a transaction that is long enough |
| 542 |
to contain the whole block, then all writes into the lock will be elided |
| 543 |
and the two transactions will not conflict with each other. As usual, |
| 544 |
they will be serialized in some order: one of the two will appear to run |
| 545 |
before the other. Simply, each of them executes an "acquire" followed |
| 546 |
by a "release" in the same transaction. As explained above, the lock |
| 547 |
state goes from "unacquired" to "unacquired" and can thus be left |
| 548 |
unchanged. |
| 549 |
|
| 550 |
This approach can gracefully fail: unlike atomic sections, there is no |
| 551 |
guarantee that the transaction runs until the end of the block. If you |
| 552 |
perform any input/output while you hold the lock, the transaction will |
| 553 |
end as usual just before the input/output operation. If this occurs, |
| 554 |
then the lock elision mode is cancelled and the lock's "acquired" state |
| 555 |
is really written. |
| 556 |
|
| 557 |
Even if the lock is really acquired already, a transaction doesn't have |
| 558 |
to wait for it to become free again. It can enter the elision-mode anyway |
| 559 |
and tentatively execute the content of the block. It is only at the end, |
| 560 |
when trying to commit, that the thread will pause. As soon as the real |
| 561 |
value stored in the lock is switched back to "unacquired", it can then |
| 562 |
proceed and attempt to commit its already-executed transaction (which |
| 563 |
can fail and abort and restart from the scratch, as usual). |
| 564 |
|
| 565 |
Note that this is all *not implemented yet,* but we expect it to work |
| 566 |
even if you acquire and release several locks. The elision-mode |
| 567 |
transaction will extend until the first lock you acquired is released, |
| 568 |
or until the code performs an input/output or a wait operation (for |
| 569 |
example, waiting for another lock that is currently not free). In the |
| 570 |
common case of acquiring several locks in nested order, they will all be |
| 571 |
elided by the same transaction. |
| 572 |
|
| 573 |
.. _`software lock elision`: https://www.repository.cam.ac.uk/handle/1810/239410 |
| 574 |
|
| 575 |
|
| 576 |
Miscellaneous functions |
| 577 |
----------------------- |
| 578 |
|
| 579 |
* First, note that the ``transaction`` module is found in the file |
| 580 |
``lib_pypy/transaction.py``. This file can be copied around to |
| 581 |
execute the same programs on CPython or on non-STM PyPy, with |
| 582 |
fall-back behavior. (One case where the behavior differs is |
| 583 |
``atomic``, which is in this fall-back case just a regular lock; so |
| 584 |
``with atomic`` only prevent other threads from entering other |
| 585 |
``with atomic`` sections, but won't prevent other threads from |
| 586 |
running non-atomic code.) |
| 587 |
|
| 588 |
* ``transaction.getsegmentlimit()``: return the number of "segments" in |
| 589 |
this pypy-stm. This is the limit above which more threads will not be |
| 590 |
able to execute on more cores. (Right now it is limited to 4 due to |
| 591 |
inter-segment overhead, but should be increased in the future. It |
| 592 |
should also be settable, and the default value should depend on the |
| 593 |
number of actual CPUs.) If STM is not available, this returns 1. |
| 594 |
|
| 595 |
* ``__pypy__.thread.signals_enabled``: a context manager that runs its |
| 596 |
block of code with signals enabled. By default, signals are only |
| 597 |
enabled in the main thread; a non-main thread will not receive |
| 598 |
signals (this is like CPython). Enabling signals in non-main |
| 599 |
threads is useful for libraries where threads are hidden and the end |
| 600 |
user is not expecting his code to run elsewhere than in the main |
| 601 |
thread. |
| 602 |
|
| 603 |
* ``pypystm.exclusive_atomic``: a context manager similar to |
| 604 |
``transaction.atomic`` but which complains if it is nested. |
| 605 |
|
| 606 |
* ``transaction.is_atomic()``: return True if called from an atomic |
| 607 |
context. |
| 608 |
|
| 609 |
* ``pypystm.count()``: return a different positive integer every time |
| 610 |
it is called. This works without generating conflicts. The |
| 611 |
returned integers are only roughly in increasing order; this should |
| 612 |
not be relied upon. |
| 613 |
|
| 614 |
|
| 615 |
More details about conflicts |
| 616 |
---------------------------- |
| 617 |
|
| 618 |
Based on Software Transactional Memory, the ``pypy-stm`` solution is |
| 619 |
prone to "conflicts". To repeat the basic idea, threads execute their code |
| 620 |
speculatively, and at known points (e.g. between bytecodes) they |
| 621 |
coordinate with each other to agree on which order their respective |
| 622 |
actions should be "committed", i.e. become globally visible. Each |
| 623 |
duration of time between two commit-points is called a transaction. |
| 624 |
|
| 625 |
A conflict occurs when there is no consistent ordering. The classical |
| 626 |
example is if two threads both tried to change the value of the same |
| 627 |
global variable. In that case, only one of them can be allowed to |
| 628 |
proceed, and the other one must be either paused or aborted (restarting |
| 629 |
the transaction). If this occurs too often, parallelization fails. |
| 630 |
|
| 631 |
How much actual parallelization a multithreaded program can see is a bit |
| 632 |
subtle. Basically, a program not using ``transaction.atomic`` or |
| 633 |
eliding locks, or doing so for very short amounts of time, will |
| 634 |
parallelize almost freely (as long as it's not some artificial example |
| 635 |
where, say, all threads try to increase the same global counter and do |
| 636 |
nothing else). |
| 637 |
|
| 638 |
However, if the program requires longer transactions, it comes |
| 639 |
with less obvious rules. The exact details may vary from version to |
| 640 |
version, too, until they are a bit more stabilized. Here is an |
| 641 |
overview. |
| 642 |
|
| 643 |
Parallelization works as long as two principles are respected. The |
| 644 |
first one is that the transactions must not *conflict* with each |
| 645 |
other. The most obvious sources of conflicts are threads that all |
| 646 |
increment a global shared counter, or that all store the result of |
| 647 |
their computations into the same list --- or, more subtly, that all |
| 648 |
``pop()`` the work to do from the same list, because that is also a |
| 649 |
mutation of the list. (You can work around it with |
| 650 |
``transaction.stmdict``, but for that specific example, some STM-aware |
| 651 |
queue should eventually be designed.) |
| 652 |
|
| 653 |
A conflict occurs as follows: when a transaction commits (i.e. finishes |
| 654 |
successfully) it may cause other transactions that are still in progress |
| 655 |
to abort and retry. This is a waste of CPU time, but even in the worst |
| 656 |
case scenario it is not worse than a GIL, because at least one |
| 657 |
transaction succeeds (so we get at worst N-1 CPUs doing useless jobs and |
| 658 |
1 CPU doing a job that commits successfully). |
| 659 |
|
| 660 |
Conflicts do occur, of course, and it is pointless to try to avoid them |
| 661 |
all. For example they can be abundant during some warm-up phase. What |
| 662 |
is important is to keep them rare enough in total. |
| 663 |
|
| 664 |
Another issue is that of avoiding long-running so-called "inevitable" |
| 665 |
transactions ("inevitable" is taken in the sense of "which cannot be |
| 666 |
avoided", i.e. transactions which cannot abort any more). Transactions |
| 667 |
like that should only occur if you use ``atomic``, |
| 668 |
generally because of I/O in atomic blocks. They work, but the |
| 669 |
transaction is turned inevitable before the I/O is performed. For all |
| 670 |
the remaining execution time of the atomic block, they will impede |
| 671 |
parallel work. The best is to organize the code so that such operations |
| 672 |
are done completely outside ``atomic``. |
| 673 |
|
| 674 |
(This is not unrelated to the fact that blocking I/O operations are |
| 675 |
discouraged with Twisted, and if you really need them, you should do |
| 676 |
them on their own separate thread.) |
| 677 |
|
| 678 |
In case lock elision eventually replaces atomic sections, we wouldn't |
| 679 |
get long-running inevitable transactions, but the same problem occurs |
| 680 |
in a different way: doing I/O cancels lock elision, and the lock turns |
| 681 |
into a real lock. This prevents other threads from committing if they |
| 682 |
also need this lock. (More about it when lock elision is implemented |
| 683 |
and tested.) |
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
Implementation |
| 688 |
============== |
| 689 |
|
| 690 |
XXX this section mostly empty for now |
| 691 |
|
| 692 |
|
| 693 |
Technical reports |
| 694 |
----------------- |
| 695 |
|
| 696 |
STMGC-C7 is described in detail in a `technical report`__. |
| 697 |
|
| 698 |
A separate `position paper`__ gives an overview of our position about |
| 699 |
STM in general. |
| 700 |
|
| 701 |
.. __: https://bitbucket.org/pypy/extradoc/src/extradoc/talk/dls2014/paper/paper.pdf |
| 702 |
.. __: https://bitbucket.org/pypy/extradoc/src/extradoc/talk/icooolps2014/ |
| 703 |
|
| 704 |
|
| 705 |
Reference to implementation details |
| 706 |
----------------------------------- |
| 707 |
|
| 708 |
The core of the implementation is in a separate C library called |
| 709 |
stmgc_, in the c7_ subdirectory (current version of pypy-stm) and in |
| 710 |
the c8_ subdirectory (bleeding edge version). Please see the |
| 711 |
`README.txt`_ for more information. In particular, the notion of |
| 712 |
segment is discussed there. |
| 713 |
|
| 714 |
.. _stmgc: https://bitbucket.org/pypy/stmgc/src/default/ |
| 715 |
.. _c7: https://bitbucket.org/pypy/stmgc/src/default/c7/ |
| 716 |
.. _c8: https://bitbucket.org/pypy/stmgc/src/default/c8/ |
| 717 |
.. _`README.txt`: https://bitbucket.org/pypy/stmgc/raw/default/c7/README.txt |
| 718 |
|
| 719 |
PyPy itself adds on top of it the automatic placement of read__ and write__ |
| 720 |
barriers and of `"becomes-inevitable-now" barriers`__, the logic to |
| 721 |
`start/stop transactions as an RPython transformation`__ and as |
| 722 |
`supporting`__ `C code`__, and the support in the JIT (mostly as a |
| 723 |
`transformation step on the trace`__ and generation of custom assembler |
| 724 |
in `assembler.py`__). |
| 725 |
|
| 726 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/readbarrier.py |
| 727 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/memory/gctransform/stmframework.py |
| 728 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/inevitable.py |
| 729 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/jitdriver.py |
| 730 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/src_stm/stmgcintf.h |
| 731 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/translator/stm/src_stm/stmgcintf.c |
| 732 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/jit/backend/llsupport/stmrewrite.py |
| 733 |
.. __: https://bitbucket.org/pypy/pypy/raw/stmgc-c7/rpython/jit/backend/x86/assembler.py |
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
See also |
| 738 |
======== |
| 739 |
|
| 740 |
See also |
| 741 |
https://bitbucket.org/pypy/pypy/raw/default/pypy/doc/project-ideas.rst |
| 742 |
(section about STM). |