Created
April 19, 2012 22:36
-
-
Save dcolish/2424660 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <pthread.h> | |
| #include <stdio.h> | |
| #include "Python.h" | |
| #define atomic_int_add(ptr, val) __sync_add_and_fetch(&ptr, val) | |
| static PyObject* | |
| int_add(PyObject *self, PyObject *args) | |
| { | |
| int avalue, bvalue; | |
| if (!PyArg_ParseTuple(args, "ii", &avalue, &bvalue)) | |
| return NULL; | |
| return Py_BuildValue("i", atomic_int_add(avalue, bvalue)); | |
| } | |
| static PyMethodDef AtomicMethods[] = { | |
| {"int_add", int_add, METH_VARARGS, "Atomically increment an integer"}, | |
| {NULL, NULL, 0, NULL} | |
| }; | |
| PyMODINIT_FUNC | |
| initatomic(void) | |
| { | |
| Py_InitModule("atomic", AtomicMethods); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from setuptools import setup, Extension | |
| atomic = Extension('atomic', | |
| sources=['atomic_py.c']) | |
| setup(name='AtomicPy', | |
| version='dev', | |
| ext_modules=[atomic] | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Run test.py with 1 for atomic, 0 for non-AtomicWorker | |
| """ | |
| import sys | |
| import threading | |
| import atomic | |
| foo = 0 | |
| class Worker(threading.Thread): | |
| def run(self): | |
| global foo | |
| while foo < 100: | |
| foo += 1 | |
| print foo | |
| class AtomicWorker(threading.Thread): | |
| def run(self): | |
| global foo | |
| while foo < 100: | |
| foo = atomic.int_add(foo, 1) | |
| print foo | |
| def main(atomic): | |
| workers = {} | |
| for _ in range(2): | |
| if atomic: | |
| thread = AtomicWorker() | |
| else: | |
| thread = Worker() | |
| thread.start() | |
| workers[thread.name] = thread | |
| for _, worker in workers.items(): | |
| worker.join() | |
| if __name__ == '__main__': | |
| sys.setcheckinterval(0) | |
| main(atomic=eval(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment