-
-
Save Tapanhaz/865fe06ac24ff1ea027ed503bd452e5f to your computer and use it in GitHub Desktop.
Basic demonstration of how to use pthreads (POSIX threads) in Cython.
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 cython.operator cimport dereference | |
| from posix.unistd cimport usleep | |
| from libc.stdio cimport printf | |
| from libc.stdint cimport intptr_t | |
| 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) noexcept 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 intptr_t retval = <intptr_t>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 = %ld\n", <intptr_t>retval1) | |
| printf("thread 2 returned value = %ld\n", <intptr_t>retval2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment