實驗一
pthread在iOS上是否可以像在linux上一樣使用?
有如下代碼:
//a.h #ifndef __A_H__ #define __A_H__ void testSleep(int t); void testPthread(int n); #endif //a.c #include "a.h" #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> void testSleep(int t) { printf("testSleep:\n"); int i; for (i=0; i<10; i++) { printf("sleep...\n"); usleep(t*1000); printf("return...\n"); } } void *thrFun(void *p) { int t = (int)p; int i; for (i = 0; i<5; i++) { printf("thrFun %d\n", t); sleep(1); } } void testPthread(int n) { void *retval; pthread_t *tid = (pthread_t *)malloc(sizeof(pthread_t)*n); int i; for (i=0; i<n; i++) pthread_create(&tid[i], NULL, thrFun, (void *)i); for (i=0; i<n; i++) pthread_join(tid[i], &retval); }
編譯成靜態庫:
gcc -c -arch i386 a.c
ar -r liba.a a.o
新建一個工程, 並把a.h和liba.a加入工程.
在某個函數中調用testPthread(5)
模擬器中運行出錯:
Detected an attempt to call a symbol in system libraries that is not present on the iPhone:
pthread_join$UNIX2003 called from function testPthread in image test-lib1.
thrFun 1
Detected an attempt to call a symbol in system libraries that is not present on the iPhone:
sleep$UNIX2003 called from function thrFun in image test-lib1.
thrFun 2
thrFun 3
thrFun 4
thrFun 0
可見並不能完全像在linux下一樣使用.
------------------------分割線 ---------------------------------
接上面的問題,開始以為pthread不能在iOS上使用
nm liba.a查看, 輸出如下:
liba.a(a.o):
U _malloc
U _printf
U _pthread_create
U _pthread_join$UNIX2003
U _puts
00000000 T _testPrint
00000100 T _testPthread
00000020 T _testSleep
000000a0 T _thrFun
U _usleep$UNIX2003
看來是編譯選項的問題, 簡單的用 -arch i386不夠,應該是少了某個選項.
----------------------- 分割線 -------------------------------------
嘗試用xcode來編譯
新建工程,如上圖,選擇Cocoa Touch Static Library, 這里命名為abc
建好之后, 把上面自動生成的兩個文件刪除,把上面的兩個文件a.h a.c拖入工程
然后選擇build
遇到一個問題, libabc.a一直是紅色(即文件不存在)
實際上只有你編譯了iOS Device版本,這里的紅色才消失.
模擬器版本的libabc.a已經生成成功了,那么它在哪呢?
可以參考這個路徑取找
/Users/robin/Library/Developer/Xcode/DerivedData/abc-atlqvsfwteridoabdmjccgcalgnu/Build/Products/Debug-iphonesimulator
/Users/robin/Library/Developer/Xcode/DerivedData/abc-atlqvsfwteridoabdmjccgcalgnu/Build/Products/Debug-iphoneos
前者是模擬器版本的輸出目錄
后者是模擬器版本的輸出目錄
nm libabc.a 輸出:
libabc.a(a.o):
000007c8 s EH_frame0
U _malloc
U _printf
U _pthread_create
U _pthread_join
00000000 T _testPrint
000007e0 S _testPrint.eh
00000130 T _testPthread
00000834 S _testPthread.eh
00000030 T _testSleep
000007fc S _testSleep.eh
000000c0 T _thrFun
00000818 S _thrFun.eh
U _usleep
后面已經沒有UNIX2003后綴了.
總結:
我最初的目的是想把一個C語言寫的庫(里面用到多線程)移植到iOS端,用gcc -arch i386編譯通過之后,開始做測試,發現每次一調用到usleep就掛掉。
一開始覺得可能是不能用sleep, 不能用pthread之類的,然后有了上面的實驗。結論就是,一開始的猜測是不正確的,是編譯的問題,導致運行時發現函數
函數未定義。