从LINUX到OSX的多线程代码

时间:2013-05-07 16:53:32

标签: c multithreading concurrency semaphore ucontext

对于一个类项目,我们使用ucontext.h在Linux中用C89编写了信号量。我的导师写了大部分代码:

#include <ucontext.h>

typedef struct TCB {
     struct TCB     *next;
     struct TCB     *prev;
     ucontext_t      context;
} TCB_t;

void init_TCB (TCB_t *tcb, void *function, void *stackP, int stack_size)
{
    getcontext(&tcb->context);              
    tcb->context.uc_stack.ss_sp = stackP;
    tcb->context.uc_stack.ss_size = (size_t) stack_size;
    makecontext(&tcb->context, function, 0);
}

TCB_t *runQ = NULL; //global Q

void start_thread(void *function)
{ 
    TCB_t *tcb;
    void *stack;
    tcb = NewItem();
    InitQueue(tcb);
    stack = malloc(8192);
    init_TCB(tcb, function, stack, 8192);
    AddQueue(&runQ, tcb);
}

void run()
{   
    ucontext_t parent;   
    getcontext(&parent);   
    swapcontext(&parent, &(runQ->context));  
}

void yield()
{
    ucontext_t current;
    current = runQ->context;
    RotateQueue(runQ);
    swapcontext(&current, &(runQ->context));
}

我写了大部分代码:

#include <q.h> //contains simple queueing operations that I wrote for TCBs

typedef struct semaphore{
    TCB_t *tcb;
    int value;
}semaphore_t;

void InitSem(semaphore_t *sem, int val)
{
    sem->value = val;
}

void P(semaphore_t *sem) //wait 
{
    sem->value--;
    TCB *temp = runQ;
    if (sem->value < 0) 
    {
        temp = DeleteQueue(&runQ);
        AddQueue(&(sem->tcb), temp);
    }
    swapcontext(&(temp->context), &(runQ->context));
}

void V(semaphore_t *sem) //signal
{
    sem->value++;
    if (sem->value <= 0)
    {   
        TCB_t *temp = DeleteQueue(&(sem->tcb)); 
        AddQueue(&runQ, temp);  
    }
    yield();

}

目前,此代码在Linux中100%运行。我的问题是为什么这段代码在OSX 10.8中不起作用。 (注意,我在OSX中切换到sys / ucontext.h)

我收到此错误:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5fbffb10
0x00007fff5fbffb10 in ?? ()

有什么想法吗?我真的想使用这段代码来帮助我自己练习学习和理解并发,现在课程结束了。

由于ucontext.h现在已被折旧,如果有人可以帮我选择不同的线程库并修改此代码,我也将非常感激。

0 个答案:

没有答案