我想运行一个关于“ pthread ”的示例程序,我可以在Linux上运行它,但在Mac上运行总线错误。
该程序来自“ UNIX环境中的高级编程”一章11.6 p365 :
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
void
cleanup(void *arg)
{
printf("cleanup: %s\n", (char *)arg);
}
void *
thr_fn1(void *arg)
{
printf("thread 1 start\n");
pthread_cleanup_push(cleanup, "thread 1 first handler");
pthread_cleanup_push(cleanup, "thread 1 second handler");
printf("thread 1 push complete\n");
if (arg)
{
return ((void *)1);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return ((void *)1);
}
void *
thr_fn2(void *arg)
{
printf("thread 2 start\n");
pthread_cleanup_push(cleanup, "thread 2 first handler");
pthread_cleanup_push(cleanup, "thread 2 second handler");
printf("thread 2 push complete\n");
if (arg)
{
pthread_exit((void *)2);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
int
main(void)
{
int err;
pthread_t tid1, tid2;
void *tret;
err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);
if (err != 0)
{
printf("can't create thread 1: %s\n", strerror(err));
return -1;
}
err = pthread_create(&tid2, NULL, thr_fn2, (void *)2);
if (err != 0)
{
printf("can't create thread 2: %s\n", strerror(err));
return -1;
}
err = pthread_join(tid1, &tret);
if (err != 0)
{
printf("can't join with thread 1: %s\n", strerror(err));
return -1;
}
printf("thread 1 exit code %d\n", (int)tret);
err = pthread_join(tid2, &tret);
if (err != 0)
{
printf("can't join with thread 2: %s\n", strerror(err));
return -1;
}
printf("thread 2 exit code %d\n", (int)tret);
return 0;
}
我可以在Linux上运行它:
$ uname Linux localhost.localdomain 3.14.4-200.fc20.x86_64 #1 SMP Tue May 13 13:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux $ ./pthread_cleanup thread 2 start thread 2 push complete cleanup: thread 2 second handler cleanup: thread 2 first handler thread 1 start thread 1 push complete thread 1 exit code 1 thread 2 exit code 2
但是我在Mac上得到了“Bus err:10”:
$ uname -s -r -v -m -i -o Darwin 13.4.0 Darwin Kernel Version 13.4.0: Sun Aug 17 19:50:11 PDT 2014; root:xnu-2422.115.4~1/RELEASE_X86_64 x86_64 MacBookPro11,1 Darwin $ ./pthread_cleanup thread 1 start thread 2 start thread 1 push complete thread 2 push complete cleanup: thread 2 second handler Bus error: 10
使用“lldb”调试它:
$ lldb pthread_cleanup (lldb) target create "pthread_cleanup" Current executable set to 'pthread_cleanup' (x86_64). (lldb) run Process 19696 launched: '/path/to/pthread_cleanup' (x86_64) thread 1 start thread 2 start thread 1 push complete thread 2 push complete Process 19696 stopped * thread #2: tid = 0x3bc9eb, 0x00000001000b6000, stop reason = EXC_BAD_ACCESS (code=2, address=0x1000b6000) frame #0: 0x00000001000b6000 -> 0x1000b6000: pushq %rdx 0x1000b6002: pushq %rsp 0x1000b6004: addb %al, (%rax) 0x1000b6006: addb %al, (%rax)
我认为Mac和Linux平台之间存在一些差异。
请给我一些建议,这样我就可以了解下一步。
THX!