00001 #ifndef COMMONS_THREADS_H 00002 #define COMMONS_THREADS_H 00003 00004 #include <pthread.h> 00005 #include <sched.h> 00006 #include <sys/syscall.h> 00007 #include <sys/types.h> 00008 #include <unistd.h> 00009 00010 #include <boost/function.hpp> 00011 00012 #include <commons/check.h> 00013 #include <commons/delegates.h> 00014 #include <commons/nullptr.h> 00015 00016 namespace commons 00017 { 00018 00019 using namespace boost; 00020 00024 #undef __CPUMASK 00025 #define __CPUMASK(cpu) (static_cast<__cpu_mask>(1) << ((cpu) % __NCPUBITS)) 00026 00031 inline pid_t 00032 gettid() 00033 { 00034 return static_cast<pid_t>(syscall(SYS_gettid)); 00035 } 00036 00040 void 00041 pin_thread(int cpu) 00042 { 00043 pid_t pid = gettid(); 00044 cpu_set_t cs; 00045 CPU_ZERO(&cs); 00046 CPU_SET(cpu, &cs); 00047 sched_setaffinity(pid, sizeof(cs), &cs); 00048 } 00049 00053 inline void 00054 waitall(pthread_t* ts, int n) 00055 { 00056 for (int i = 0; i < n; i++) { 00057 check(pthread_join(ts[i], nullptr) == 0); 00058 } 00059 } 00060 00066 pthread_t 00067 spawn(const boost::function<void()>& f) 00068 { 00069 pthread_t t; 00070 return pthread_create(&t, NULL, &run_function0_null, 00071 new boost::function<void()>(f)) == 0 ? t : 0; 00072 } 00073 00074 } 00075 00076 #endif