1

所以基本上我正在做一个类项目,我们自己实现一个锁。我相当确定我的锁码是正确的,但是我的测试码不能正常工作。我们正在使用我的教授给班级的一个名为 sthreads 的 pthreads 版本。这是我的测试代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "sync.h"
#include "sthread.h"

sthread_mutex_t *mutex;
int locktest(void* arg){
    int threadNum = (int)arg;
    //int i;
    for(;;){ 
        int x  = sthread_mutex_lock(mutex);
        printf("return value: %d\n", x);
        //sleep(1);
        printf("thread %d has the lock\n", threadNum);
        sleep(1);
        sthread_mutex_unlock(mutex);
    }
    return 0;
}


int main(){
sthread_t thr1, thr2, thr3, thr4, thr5;

if (sthread_init() == -1){
    return -1;
}

if(sthread_mutex_init(mutex)){
    return -1;
}

sthread_mutex_lock(mutex);

if (sthread_create(&thr1, locktest, (void *)1) == -1){
    return -1;
}
if (sthread_create(&thr2, locktest, (void *)2) == -1){
    return -1;
}
if (sthread_create(&thr3, locktest, (void *)3) == -1){
    return -1;
}
if (sthread_create(&thr4, locktest, (void *)4) == -1){
    return -1;
}
if (sthread_create(&thr5, locktest, (void *)5) == -1){
    return -1;
}

sleep(100);
sthread_mutex_unlock(mutex);
sthread_mutex_destroy(mutex);
return 0;

}

我发现由于某种原因,即使互斥锁是全局的,每个线程都有不同的实例。我知道这一点是因为函数 locktest(每个线程运行)中对 sthread_mutex_lock(mutex) 的每次调用的返回值不是 0。这表明锁尚未初始化,因此是一个空指针,即使您看到我已初始化它主要在第二个 if 语句中。

有没有人知道为什么会这样?

4

1 回答 1

3

You never initialize mutex to point at anything, so it has the value NULL. sthread_mutex_init(mutex) isn't going to work, since it was basically passed the value NULL.

You probably want sthread_mutex_init(&mutex) (declare sthread_mutex_init as taking a sthread_mutex_t **).

于 2012-10-17T04:16:37.923 回答