• 多线程使用互斥锁的C范例


    #include <stdio.h>
    #include <sys/time.h>
    #include <pthread.h>

    int pThreadActVarMagPCID = -1;
    pthread_t pThreadActVarMagPC;
    pthread_mutex_t BACK_COMM_mutex = PTHREAD_MUTEX_INITIALIZER ;

    void *ActVarMagThread(void *pdbdata)
    {
        printf("--------------------\n");
            printf(" actvarmagthread on \n");
            printf("--------------------\n");
        while(1)
        {
             if(pthread_mutex_lock(&BACK_COMM_mutex)!=0)
            {
                        printf("ActVarMagThread BACK_COMM_mutex lock err !!\n");
                break;
            }
            usleep(40);
            if(pthread_mutex_unlock(&BACK_COMM_mutex)!=0) //unlock
                    {
                printf("ActVarMagThread pthread_mutex_unlock err !!\n");
                break;
            }
            usleep(100);
        }
        sleep(1);
    }

    int main(void)
    {
        printf("mul thread starting test \n");
        pthread_mutex_init(&BACK_COMM_mutex,NULL); 
        memset((void *)&pThreadActVarMagPC, 0, sizeof(pThreadActVarMagPC));
        if((pThreadActVarMagPCID = pthread_create(&pThreadActVarMagPC, NULL, ActVarMagThread, NULL)) != 0) 
        {
            printf("ActVarMagPC fork err !!");
            return -1;   
        }
        else
        {
            while(1)
            {
                 if(pthread_mutex_lock(&BACK_COMM_mutex)!=0)
                {
                            printf("BACK_COMM_mutex lock err !!\n");
                    break;
                }
                usleep(40);
                if(pthread_mutex_unlock(&BACK_COMM_mutex)!=0) //unlock
                        {
                    printf("pthread_mutex_unlock err \n");
                    break;
                }
                usleep(100);
            }
        }
        sleep(1);
        return 0;
    }

  • 相关阅读:
    sql count中加条件
    zero-copy总结
    问题诊断神器arthas
    rabbitmq 消息确认
    HttpRunner安装笔记(1)安装环境准备:pyenv安装
    centos7 安装rabbitmq3.4.1-1
    centos7 python2.7.5 升级python3.6.4
    测试面试必会sql(1)
    mysql5.6 无法远程连接问题解决
    Katalon 学习笔记(一)
  • 原文地址:https://www.cnblogs.com/leaven/p/1751241.html
Copyright © 2020-2023  润新知