关于#c语言#的问题:描述:set_count函数设置播放的次数,_pthread线程一直运行,当count>0时进行播放,然后count减一,一共播放count次

static int count = 0;
void *_pthread(void *param)
{
    while(1)
    {
        while(count > 0)
        {
                play();
                count--;
        }
        usleep(50000);
    }
}

void set_count(int nCount)
{
    count = nCount;
}

描述:set_count函数设置播放的次数,_pthread线程一直运行,当count>0时进行播放,然后count减一,一共播放count次;
问题:如果在播放过程中,外部调用set_count接口更新了count值,怎么保证线程再播放count次?考虑过在set_count中“count = nCount”加上读写锁,然后线程中"count--"前后加上读写锁;但还是有一种情况会异常(当play()执行后,外部调用set_count更新count,线程会把更新后的count--,这样就少了一次),不知道有没有好方法解决该问题?

lock();
play();
count--;
onclock();