I want to do some Python multithreading and bypass the GIL using ctypes.
I wrote some C code, test.c:
long long sum_range(long high)
{
long i;
long long s = 0LL;
for (i = 0L; i < high; i++)
s += (long long)i;
return s;
}
Compile and link using
gcc -O3 -g -fPIC -c -o test.o test.c
ld -shared -o libtest.so test.o
Call it from a Python 3 script:
import ctypes
import os
testlib = ctypes.cdll.LoadLibrary(os.getcwd()+"/libtest.so")
sum_range = testlib.sum_range
sum_range.argtypes = [ctypes.c_long]
sum_range.restypes = ctypes.c_longlong
iterations=100000
print("sum_range(iterations) = {}".format(sum_range(iterations)))
This gives
sum_range(iterations) = 704982704
Instead of 4999950000. What is wrong here?
PS Adding a printf
to the C code shows that the correct value of 4999950000 is being returned to the Python script.
PPS The correct value is printed when iterations
is e.g. ten times smaller, so 10000.
PPPS A similar question was raised earlier but setting restypes apparently does not fix the problem.