行云

行至水穷处,坐看云起时。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

实验一
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之类的,然后有了上面的实验。结论就是,一开始的猜测是不正确的,是编译的问题,导致运行时发现函数
函数未定义。

posted on 2013-01-11 19:42  windflying  阅读(3942)  评论(0编辑  收藏  举报