Interruptible FFI calls with pthread_kill and CancelSynchronousIO. v4
[ghc-hetmet.git] / rts / posix / OSThreads.c
index 9bcd56f..2831553 100644 (file)
 #define _GNU_SOURCE
 #endif
 
+#include "PosixSource.h"
+
+#if defined(freebsd_HOST_OS)
+/* Inclusion of system headers usually requires __BSD_VISIBLE on FreeBSD,
+ * because of some specific types, like u_char, u_int, etc. */
+#define __BSD_VISIBLE  1
+#endif
+
 #include "Rts.h"
+
 #if defined(THREADED_RTS)
-#include "OSThreads.h"
 #include "RtsUtils.h"
 #include "Task.h"
 
 #include <string.h>
 #endif
 
+#if defined(darwin_HOST_OS) || defined(freebsd_HOST_OS)
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#endif
+
 #if !defined(HAVE_PTHREAD_H)
 #error pthreads.h is required for the threaded RTS on Posix platforms
 #endif
 #include <sched.h>
 #endif
 
+#if defined(HAVE_SYS_CPUSET_H)
+#include <sys/param.h>
+#include <sys/cpuset.h>
+#endif
+
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <mach/mach.h>
 #endif
 
+#ifdef HAVE_SIGNAL_H
+# include <signal.h>
+#endif
+
 /*
  * This (allegedly) OS threads independent layer was initially
  * abstracted away from code that used Pthreads, so the functions
@@ -202,6 +224,10 @@ getNumberOfProcessors (void)
         nproc = sysconf(_SC_NPROCESSORS_ONLN);
 #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF)
         nproc = sysconf(_SC_NPROCESSORS_CONF);
+#elif defined(darwin_HOST_OS) || defined(freebsd_HOST_OS)
+        size_t size = sizeof(nat);
+        if(0 != sysctlbyname("hw.ncpu",&nproc,&size,NULL,0))
+            nproc = 1;
 #else
         nproc = 1;
 #endif
@@ -224,7 +250,7 @@ setThreadAffinity (nat n, nat m)
     nproc = getNumberOfProcessors();
     CPU_ZERO(&cs);
     for (i = n; i < nproc; i+=m) {
-        CPU_SET(n, &cs);
+        CPU_SET(i, &cs);
     }
     sched_setaffinity(0, sizeof(cpu_set_t), &cs);
 }
@@ -243,6 +269,23 @@ setThreadAffinity (nat n, nat m GNUC3_ATTRIBUTE(__unused__))
                      THREAD_AFFINITY_POLICY_COUNT);
 }
 
+#elif defined(HAVE_SYS_CPUSET_H) /* FreeBSD 7.1+ */
+void
+setThreadAffinity(nat n, nat m)
+{
+       nat nproc;
+       cpuset_t cs;
+       nat i;
+
+       nproc = getNumberOfProcessors();
+       CPU_ZERO(&cs);
+
+       for (i = n; i < nproc; i += m)
+               CPU_SET(i, &cs);
+
+       cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &cs);
+}
+
 #else
 void
 setThreadAffinity (nat n GNUC3_ATTRIBUTE(__unused__), 
@@ -251,6 +294,12 @@ setThreadAffinity (nat n GNUC3_ATTRIBUTE(__unused__),
 }
 #endif
 
+void
+interruptOSThread (OSThreadId id)
+{
+    pthread_kill(id, SIGPIPE);
+}
+
 #else /* !defined(THREADED_RTS) */
 
 int