c - 在c中使用pthreads,出于某种原因,每个pthread都有一个不同的锁实例

标签 c pthreads semaphore

所以基本上我正在做一个类项目,我们自己实现一个锁。我相当确定我的锁定代码是正确的,但是我的测试代码无法正常工作。我们正在使用我的教授给全类的称为 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 语句中的 main 中。

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

最佳答案

您永远不会将 mutex 初始化为指向任何东西,因此它的值为 NULLsthread_mutex_init(mutex) 不会工作,因为它基本上传递了值 NULL

可能想要sthread_mutex_init(&mutex)(将sthread_mutex_init声明为采用sthread_mutex_t **)。

关于c - 在c中使用pthreads,出于某种原因,每个pthread都有一个不同的锁实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926995/

相关文章:

c - C 中的结构体被用零填充

c - 使用 pthread 的简单死锁示例

c++ - 在 for 循环中将结构传递给 pthread 的正确方法

c++ - 阻塞队列竞争条件?

c - 如何在 C 中表示类似 Python 的字典

c - 强制传输C中的所有串行数据

c++ - eclipse同步的C/C++项目同步失败

c++ - 帮助使用信号量和线程

Java 一个临界区多个信号量

c# - 在 IDisposable 派生类中应该在哪里释放单例互斥量?