• 多线程使用互斥锁的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;
    }

  • 相关阅读:
    android 调试卡在:Waiting for Debugger
    将DataTable 数据插入 SQL SERVER 数据库
    android adb shell 命令大全
    GeoServer地图开发解决方案(四):发布Web地图服务(WMS)篇
    GeoServer地图开发解决方案(三):部署地图数据篇
    GeoServer地图开发解决方案(二):地图数据处理篇
    GeoServer地图开发解决方案(一):环境搭建篇
    pl/sql developer 导入sql脚本
    Myeclipse2013破解方法
    CentOS 6.4下架设NFS服务器
  • 原文地址:https://www.cnblogs.com/leaven/p/1751241.html
Copyright © 2020-2023  润新知