Chinaunix首页 | 论坛 | 博客
  • 博客访问: 545453
  • 博文数量: 99
  • 博客积分: 5015
  • 博客等级: 大校
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-28 23:08
文章存档

2011年(7)

2010年(6)

2009年(86)

我的朋友

分类: LINUX

2009-08-27 16:29:01

POSIX的Linux操作系统没有提供线程挂起和恢复的例程,在网上找了找,看到一个老外写的程序,感觉想法不错,放在这里大家分享一下。理论上应该可以实现,不过我没有试,给大家提供一个参考。 (在读取缓存里的数据时,当缓存中没有数据最好把线程挂起)
void CPrcThread ::suspend()
{
    ifdef WIN32
    //do windows specific things here...
    #endif

    #ifdef __linux__
    pthread_mutex_lock(&mutex);
    flag--;
    pthread_mutex_unlock(&mutex);
    #endif
}

void CPrcThread ::resume()
{
        #ifdef WIN32
        //do windows specific things here...
        #endif

        #ifdef __linux__
        pthread_mutex_lock(&mutex);
        flag++;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        #endif
}

void* CPrcThread ::threadFunc(void* pParameter)
{

    while(1)
    {

          #ifdef WIN32
        //do windows specific things here...
        //no member variables accessed here so its ok...
        #endif


        #ifdef __linux__
          pthread_mutex_lock(&mutex);
          while(flag <= 0)
          {
                  pthread_cond_wait(&cond, &mutex);
          }
          pthread_mutex_unlock(&mutex);
          #endif


          //actual thread work here

    }

}
阅读(6827) | 评论(0) | 转发(3) |
给主人留下些什么吧!~~