Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Forked from jerryvig/pthreads_cython.pyx
Last active December 4, 2022 18:59
Show Gist options
  • Save SpotlightKid/16d976b764708431959f4776d20ddd25 to your computer and use it in GitHub Desktop.
Save SpotlightKid/16d976b764708431959f4776d20ddd25 to your computer and use it in GitHub Desktop.
Basic demonstration of how to use pthreads (POSIX threads) in Cython.
# cython: language_level=3, boundscheck=False
from cython.operator cimport dereference
from libc.stdio cimport printf
from posix.unistd cimport usleep
cdef extern from "pthread.h" nogil:
ctypedef int pthread_t
ctypedef struct pthread_attr_t:
pass
cdef int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
cdef int pthread_join(pthread_t thread, void **retval)
cdef void *perform_work(void *args) nogil:
"""Target thread function."""
cdef int thread_index = dereference(<int*>args)
if thread_index == 2:
usleep(1000000)
else:
usleep(3000000)
printf("printing from thread # %d\n", thread_index)
cdef int retval = thread_index + 1
return <void*>retval
def main():
"""The main routine and application entry point of this module."""
cdef pthread_t thread1
cdef pthread_t thread2
cdef int arg1 = 1
cdef int arg2 = 2
cdef void *retval1
cdef void *retval2
pthread_create(&thread1, NULL, perform_work, &arg1)
pthread_create(&thread2, NULL, perform_work, &arg2)
printf("IN main all threads created.\n")
pthread_join(thread1, &retval1)
pthread_join(thread2, &retval2)
printf("DONE JOINING ALL OF THE THREADS\n")
printf("thread 1 returned value = %d\n", <int>retval1)
printf("thread 2 returned value = %d\n", <int>retval2)
from setuptools import setup
from Cython.Build import cythonize
setup(
name='pthreads test app',
ext_modules=cythonize("pthreads_cython.pyx"),
zip_safe=False,
)
@SpotlightKid
Copy link
Author

$ python setup.py build_ext --inplace
$ python
Python 3.10.8 (main, Nov  1 2022, 14:18:21) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pthreads_cython import main
>>> main()
IN main all threads created.
printing from thread # 2
printing from thread # 1
DONE JOINING ALL OF THE THREADS
thread 1 returned value = 2
thread 2 returned value = 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment