Skip to content

Instantly share code, notes, and snippets.

@flazz
Last active August 20, 2016 02:45
Show Gist options
  • Save flazz/dc2ed4e9a8811ffd864aebe8479483f4 to your computer and use it in GitHub Desktop.
Save flazz/dc2ed4e9a8811ffd864aebe8479483f4 to your computer and use it in GitHub Desktop.
python callbacks not making new thread on every cb invocation
/* cc -shared conc.c -o conc.dynlib */
#include <pthread.h>
#include <stdio.h>
typedef void (*cb_t)(int);
pthread_t t;
cb_t cb;
void set_notify(cb_t cb0) {
cb = cb0;
}
void* run() {
printf("C thread - in thread begin\n");
int i;
for (i = 0; i < 3; i++) {
printf("C thread - in thread; notify begin: %d\n", i);
cb(i);
printf("C thread - in thread; notify end: %d\n", i);
}
printf("C thread - in thread; done\n");
return NULL;
}
void start() {
printf("C thread - starting thread\n");
pthread_create(&t, NULL, *run, NULL);
pthread_join(t, NULL);
printf("C thread - joined thread\n");
}
#! /usr/bin/env python
import threading
import ctypes
import os
print os.getpid()
ev = threading.Event()
def t_id():
t = threading.current_thread()
id = "%d-%s" % (t.ident, t.name)
return id
def notifier(n):
print 'PYTHON - notify begin', t_id(), n
ev.set()
print 'PYTHON - notify done', t_id(), n
def consumer():
print 'PYTHON - consume waiting', t_id()
ev.wait()
print 'PYTHON - consume done', t_id()
ev.clear()
lib = ctypes.CDLL('./conc.dynlib')
print('Loaded lib {0}'.format(lib))
cb_t = ctypes.CFUNCTYPE(None, ctypes.c_int)
lib.set_notify.argtypes=[cb_t]
lib.set_notify.restype=None
lib.start.argtypes=[]
lib.start.restype=None
cb = cb_t(notifier)
lib.set_notify(cb)
t2 = threading.Thread(group=None, target=consumer)
t2.start()
lib.start()
t2.join()
print 'done'
65464
Loaded lib <CDLL './conc.dynlib', handle 7fdc436116f0 at 10ad76190>
PYTHON - consume waiting 123145306509312-Thread-1
C thread - starting thread
C thread - in thread begin
C thread - in thread; notify begin: 0
PYTHON - notify begin 123145307045888-Dummy-2 0
PYTHON - notify done 123145307045888-Dummy-2 0
C thread - in thread; notify end: 0
C thread - in thread; notify begin: 1
PYTHON - notify begin 123145307045888-Dummy-2 1
PYTHON - notify done 123145307045888-Dummy-2 1
C thread - in thread; notify end: 1
C thread - in thread; notify begin: 2
PYTHON - consume done 123145306509312-Thread-1
PYTHON - notify begin 123145307045888-Dummy-2 2
PYTHON - notify done 123145307045888-Dummy-2 2
C thread - in thread; notify end: 2
C thread - in thread; done
C thread - joined thread
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment