zoukankan      html  css  js  c++  java
  • 使用读写锁

    /* 
    FileName: rwlock.c 
    Date: 20100310 
    Desc: g++ rwlock.c -lpthread -o demo 
          使用读写锁, 在读大于写情况下使用读写锁
    */  
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <pthread.h>
    #include <signal.h>
    int isRun = 1;  // 程序运行标志
    struct ConfigInfo{
            pthread_rwlock_t rwlock;
            char path[128+1];
            int timeout;
    };
    void* thread_fun(void * arg)
    {
            struct ConfigInfo* p = (struct ConfigInfo*)arg;
            while (isRun)
            {
                    pthread_rwlock_rdlock(&p->rwlock);        // 加读锁
                    printf("tid=%ul, path=%s, timeout=%d\n", pthread_self(), p->path, p->timeout);
                    pthread_rwlock_unlock(&p->rwlock);  // 解锁
                    sleep(2);
            }
            return (void*)1;
    }
    void sig_fun(int signo)
    {
            isRun = 0;
    }
    int main(int argc, char* argv[])
    {
            signal(SIGINT, sig_fun);
            int i, ret;
            pthread_t tid[10];
            struct ConfigInfo info;
            pthread_rwlock_init(&info.rwlock, NULL); // 初始化读写锁
            for (i = 0;i < 10;i++)
            {
                    ret = pthread_create(&tid[i], NULL, thread_fun, (void*)&info);
                    if (ret != 0)
                    {
                            printf("%d. pthread_create() is Error\n", i);
                            exit(-1);
                    }
            }
            i = 0;
            while (isRun)
            {
                    if (i++%5 == 0)   // 某情况下,修改读写锁保护的数据结构。
                    {
                            pthread_rwlock_wrlock(&info.rwlock);  // 加写锁
                            memset(info.path, 0x00sizeof(info.path));
                            strcpy(info.path, "/home/pc/a.txt");
                            info.timeout = i%8;
                            pthread_rwlock_unlock(&info.rwlock);  // 解锁
                    }
                    sleep(1);
            }
            for (i = 0;i < 10;i++)
            {
                    ret = pthread_join(tid[i], NULL);
                    if (ret != 0)
                    {
                            printf("%d. pthread_join() is Error\n", i);
                            exit(-1);
                    }
            }
            pthread_rwlock_destroy(&info.rwlock); // 销毁读写锁
            return 0;
    }
  • 相关阅读:
    实现雨滴的效果
    rainyday.js
    XHTML1.0版本你知道么,跟html5版本有什么区别
    背景图合并用在什么地方最适合,有什么优点
    什么是css hack
    用一两句话说一下你对“盒模型”这个概念的理解,和它都涉及到哪些css属性
    块属性标签和行内属性标签及样式优先级
    【Loadrunner】Loadrunner 手动关联技术
    【黑盒测试】测试用例的常用方法
    【Linux】阿里云服务器部署--禅道
  • 原文地址:https://www.cnblogs.com/toosuo/p/2196183.html
Copyright © 2011-2022 走看看