linux多线程的互斥锁问题

1、原因

写这篇记录一下的原因是,有个项目(NPU)存在一点问题,而且是那种比较让人头疼麻烦崩溃的问题,人脸数据一开始传的好好地,隔三差五就会没数据,重启程序后又回复(他们说是这样,我自己倒是还没见过没数据推上来的时候)

2、多线程中的互斥锁

这是在源程序中看到的一个可疑的地方,简单来说就是,在将任务压到队列中的时候,需要去获取相应的锁(防止数据出现时间上的问题)但是问题是,该锁的初始化步骤还没有进行到,但是执行过程却是没啥问题,对互斥量加锁(pthread_mutex_lock)或者解锁(pthread_mutex_unlock)的时候互斥量却还没有进行初始化,就是还没有pthread_mutex_init,这从严谨方面看绝对是有问题的,不过若是初始化的操作和定义时的赋值操作是一样的(比如说都给的是0)那按道理初不初始化又似乎没有影响,自己于是写了个测试程序,结果卧槽看起来还真的是没有影响。但是又有网上大神说了"互斥锁对象必须通过其API初始化,不能使用memset或者复制初始化"这就让我头大了…

3、测试代码

/*程序让子线程打印小写,主控线程打印大写,用sleep模拟CPU易主*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex;      //定义锁

void *tfn(void *arg)
{
    srand(time(NULL));

    while (1) {
        pthread_mutex_lock(&mutex);

        printf("hello ");
        sleep(rand() % 3);	/*模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误*/
        printf("world\n");
        pthread_mutex_lock(&mutex);

        sleep(rand() % 3);
    }

    return NULL;
}

int main(void)
{
    int flg = 5;
    pthread_t tid;
    srand(time(NULL));

    pthread_mutex_init(&mutex, NULL);  // 就是这个地方,若是注释了,结果似乎没有啥影响......
    pthread_create(&tid, NULL, tfn, NULL);
    while (flg--) {

        pthread_mutex_lock(&mutex);

        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        pthread_mutex_unlock(&mutex);

        sleep(rand() % 3);

    }
    pthread_cancel(tid);
    pthread_join(tid, NULL);

    pthread_mutex_destroy(&mutex);  

    return 0;
}

不去注释,一切严谨结果:
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
hello world
hello world
HELLO WORLD
hello world
hello world
hello world
HELLO WORLD
hello world
hello world
HELLO WORLD
hello world
HELLO WORLD
hello world
hello world
HELLO WORLD

将初始化API注释了:
HELLO WORLD
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
HELLO WORLD
HELLO WORLD
hello world
hello world
HELLO WORLD
HELLO WORLD
hello world
HELLO WORLD
hello world
HELLO WORLD
hello world
hello world
hello world
HELLO WORLD
HELLO WORLD

结果反正我肉眼看上去看不出什么差别…
这个初始化的函数设计绝对不可能是可有可无的,不过到现在还是不知道不去初始化会造成什么问题,求懂得人给个说法啊

发布了46 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42718004/article/details/99305820