00001
00002
00003 #ifndef MULTITHREAD_H
00004 #define MULTITHREAD_H
00005
00006 #ifdef MULTITHREAD
00007
00008 #include <pthread.h>
00009
00010 #if defined(_ENABLE_X86_ASM)
00011
00012 class AtomicCounter {
00013 int count;
00014 public:
00015 AtomicCounter(int c) : count(c) {}
00016 void inc()
00017 {
00018 #ifdef SMP
00019 __asm__ __volatile__ ("lock; add $1, %0"
00020 : : "m" (count) : "memory");
00021 #else
00022 __asm__ __volatile__ ("add $1, %0"
00023 : : "m" (count) : "memory");
00024 #endif
00025 }
00026 bool dec()
00027 {
00028 int tmp;
00029 #ifdef SMP
00030 __asm__ __volatile__ ("lock; sub $1, %1\n\tmov $0, %0\n\tjle out%=\n\tmov $1, %0\n\tout%=:"
00031 : "=r" (tmp): "m" (count) : "memory");
00032 #else
00033 __asm__ __volatile__ ("sub $1, %1\n\tmov $0, %0\n\tjle out%=\n\tmov $1, %0\n\tout%=:"
00034 : "=r" (tmp): "m" (count) : "memory");
00035 #endif
00036 return tmp;
00037 }
00038
00039 bool unique() {return count==1;}
00040
00041 };
00042
00043
00044 class FastMutex {
00045 int spin;
00046 public:
00047 FastMutex() {spin=1;}
00048 void lock()
00049 {
00050
00051 int tmp=0;
00052 __asm__ __volatile__ ("spin%=:\n\txchg (%%eax), %0\n\tcmp $0, %0\n\tje spin%="
00053 : "=r" (tmp) : "0" (tmp), "a" (&spin) : "memory");
00054
00055 }
00056 void unlock() {spin=1;}
00057 };
00058
00059
00060 #else
00061
00062 class AtomicCounter {
00063 volatile int count;
00064 pthread_mutex_t mutex;
00065 public:
00066 AtomicCounter(int c) : count(c) {pthread_mutex_init(&mutex, NULL);}
00067 ~AtomicCounter() {pthread_mutex_destroy(&mutex);}
00068
00069 void inc()
00070 {
00071 pthread_mutex_lock(&mutex);
00072 ++count;
00073 pthread_mutex_unlock(&mutex);
00074 }
00075
00076 bool dec()
00077 {
00078 int tmp;
00079 pthread_mutex_lock(&mutex);
00080 --count;
00081 tmp=count;
00082 pthread_mutex_unlock(&mutex);
00083 return (tmp > 0);
00084 }
00085
00086 bool unique() {return count==1;}
00087
00088 };
00089
00090
00091 class FastMutex {
00092 pthread_mutex_t mutex;
00093 public:
00094 FastMutex() {pthread_mutex_init(&mutex, NULL);}
00095 ~FastMutex() {pthread_mutex_destroy(&mutex);}
00096 void lock() {pthread_mutex_lock(&mutex);}
00097 void unlock() {pthread_mutex_unlock(&mutex);}
00098 };
00099
00100
00101
00102 #endif
00103
00104 #else
00105
00106
00107 class AtomicCounter {
00108 int count;
00109 public:
00110 AtomicCounter(int c) : count (c) {}
00111 void inc() {++count;}
00112 bool dec() {--count;return (count > 0);}
00113 bool unique() {return count==1;}
00114 };
00115
00116
00117 class FastMutex {
00118 public:
00119 void lock() {}
00120 void unlock() {}
00121 };
00122
00123 #endif
00124
00125
00126
00127 #endif