-
-
Save SpotlightKid/16d976b764708431959f4776d20ddd25 to your computer and use it in GitHub Desktop.
Basic demonstration of how to use pthreads (POSIX threads) in Cython.
This file contains 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
# 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) |
This file contains 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 | |
from Cython.Build import cythonize | |
setup( | |
name='pthreads test app', | |
ext_modules=cythonize("pthreads_cython.pyx"), | |
zip_safe=False, | |
) |
Author
SpotlightKid
commented
Dec 4, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment