c - 是否有用于 C 的静态代码检查器会标记缺少的互斥锁解锁?

标签 c static clang analysis clang-tidy

<分区>

在下面的代码中,两个线程使用同一个函数,每个线程都应该在启动前获取锁。所以第一个线程获得锁,完成工作,然后离开,但没有释放锁,因为解锁命令被故意注释掉了。第二个线程永远不会获得锁,因此永远不会完成这项工作。

我创建这个简单的示例只是为了测试我正在使用的静态代码检查器是否会标记这种情况(缺少解锁),而它不会。我正在使用 CodeChecker它有 clang 静态分析器和 clang-tidy 检查器。你知道任何会标记这个的静态代码检查器吗?我认为 Coverity 可以,但我没有证明这一点的许可证。

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

pthread_t tid[2];
int counter;
pthread_mutex_t lock;

void* doSomeThing() {
    pthread_mutex_lock(&lock);

    unsigned long i = 0;
    counter += 1;
    printf("\n Job %d started\n", counter);

    for(i=0; i<(0xFFFFFFF);i++);

    printf("\n Job %d finished\n", counter);

    // pthread_mutex_unlock(&lock);

    return NULL;
}

int main(void) {
    int i = 0;
    int err;

    if (pthread_mutex_init(&lock, NULL) != 0) {
        printf("\n mutex init failed\n");
        return 1;
    }

    while(i < 2) {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        i++;
    }

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}

最佳答案

Coverity 可以通过 --concurrency 选项显示信号量锁定/解锁组合的缺陷。

查看此 article了解更多详情。

关于c - 是否有用于 C 的静态代码检查器会标记缺少的互斥锁解锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53758731/

相关文章:

c - 包含来自另一个目录的头文件

java - 静态方法的使用

c - 为什么那些函数调用没有优化?

c++ - 在 C 应用程序中运行 C++(使用 STL)函数

c - 相等性检查未按预期工作

java - java中的静态变量和多线程

c++ - 当大小仅在运行时已知时如何指定 C++ 静态 vector 大小-不需要

gcc - 在 g++ (gcc) 或 clang (llvm) 中禁止内联汇编

c++ - 编译命令成功,链接错误 undefined reference 符号 '_ZNSt3__15mutex4lockEv'

c - 在 C 中进行合并排序时不断获取垃圾值