Skip to content

Instantly share code, notes, and snippets.

@jerryvig
Last active December 4, 2022 18:57
Show Gist options
  • Save jerryvig/616296573d0e18e44c89500692a512e7 to your computer and use it in GitHub Desktop.
Save jerryvig/616296573d0e18e44c89500692a512e7 to your computer and use it in GitHub Desktop.
Basic demonstration of how to use pthreads (POSIX threads) in Cython.
from cython.operator cimport dereference
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment