= 目標 = * 以 gcc 編譯 spin_or_mutex.c * 編輯configure.ac makefile.am == spin_or_mutex.c == {{{ #!c //export LIBRARY_PATH=/usr/lib/i386-linux-gnu/ #include #include #include #include #include #include #define LOOPS 10000000 #ifdef USE_SPINLOCK pthread_spinlock_t spinlock; #else pthread_mutex_t mutex; #endif pid_t gettid() { return syscall( __NR_gettid ); } char data[LOOPS]; void *consumer(void *ptr) { int i = 0; printf("Consumer TID %lu\n", (unsigned long)gettid()); while (1) { #ifdef USE_SPINLOCK pthread_spin_lock(&spinlock); #else pthread_mutex_lock(&mutex); #endif if (i > LOOPS) { #ifdef USE_SPINLOCK pthread_spin_unlock(&spinlock); #else pthread_mutex_unlock(&mutex); #endif break; } data[i] = 0; i++; #ifdef USE_SPINLOCK pthread_spin_unlock(&spinlock); #else pthread_mutex_unlock(&mutex); #endif } return NULL; } int main() { int i; pthread_t thr1, thr2; struct timeval tv1, tv2; #ifdef USE_SPINLOCK pthread_spin_init(&spinlock, 0); #else pthread_mutex_init(&mutex, NULL); #endif // Creating the list content... for (i = 0; i < LOOPS; i++){ data[i] = 1; } // Measuring time before starting the threads... gettimeofday(&tv1, NULL); pthread_create(&thr1, NULL, consumer, NULL); pthread_create(&thr2, NULL, consumer, NULL); pthread_join(thr1, NULL); pthread_join(thr2, NULL); // Measuring time after threads finished... gettimeofday(&tv2, NULL); if (tv1.tv_usec > tv2.tv_usec) { tv2.tv_sec--; tv2.tv_usec += 1000000; } printf("Result - %ld.%ld\n", tv2.tv_sec - tv1.tv_sec, tv2.tv_usec - tv1.tv_usec); #ifdef USE_SPINLOCK pthread_spin_destroy(&spinlock); #else pthread_mutex_destroy(&mutex); #endif return 0; } }}} == 以 gcc 編譯 spin_or_mutex.c == === 編輯Makefile === {{{ #!text all: gcc spin_or_mutex.c -o spin_or_mutex clean: rm -f spin_or_mutex }}} == 執行 == {{{ $ make gcc spin_or_mutex.c -o spin_or_mutex /tmp/ccTHYKpZ.o: In function `main': spin_or_mutex.c:(.text+0xf2): undefined reference to `pthread_create' spin_or_mutex.c:(.text+0x116): undefined reference to `pthread_create' spin_or_mutex.c:(.text+0x12a): undefined reference to `pthread_join' spin_or_mutex.c:(.text+0x13e): undefined reference to `pthread_join' collect2: ld returned 1 exit status make: *** [all] Error 1 }}} === 修改 Makefile === {{{ #!text all: gcc -lpthread spin_or_mutex.c -o spin_or_mutex.o clean: rm -f spin_or_mutex.o }}} == 執行 == {{{ $ make $ ./spin_or_mutex }}} * Done! == 編輯configure.ac makefile.am == == 執行 == {{{ $ autoscan $ mv configure.scan configure.ac $ mv Makefile Makefile.in $ autoconf $ autoheader $ ./configure $ make clean }}} == 修改spin_or_mutex.c == {{{ #!c #include "config.h" // 以下略 }}} == 新增Makefile.am == {{{ #!text bin_PROGRAMS=spin_or_mutex spin_or_mutex_SOURCES=spin_or_mutex.c }}} == 產生make檔 == {{{ $ aclocal $ autoconf $ automake }}} * 修改error * 修改完後記得 {{{ $ aclocal }}} * ./confifure {{{ $ ./configure $ make }}}