记录一个有意思的现象,
假设我们启动N个线程,同时执行一个线程函数,线程函数先是进入循环进行抢占锁,然后睡眠一段时间模拟处理业务的过程,然后释放锁,然后进行下一次循环,代码如下:
std::mutex mtx;
void fun()
{
while (true)
{
mtx.lock();
std::cout << "thread_id = " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
mtx.unlock();
}
}
int main()
{
for(int i = 0; i < 10; ++i)
{
std::thread t(fun);
t.detach();
}
getchar();
return 0;
}
分析过程:
- 创建十个线程,最终只有一个线程进入循环中,抢占到mtx锁;
- 该线程睡眠1000毫秒后释放锁;
- 该线程马上又去抢占锁,而其他9个线程由于没有抢占到锁被OS调度器挂起,并且该线程的时间片极大可能还没有使用完,然后该线程将继续获得锁,其他九个线程继续阻塞在mtx上,所以会导致当前线程一直执行多次后才轮到其他的线程。
那我们添加一行代码,在unlock()后面,使得线程睡眠一秒,主动放弃其时间片,使得自身被挂起,然后操作系统会唤起其他的阻塞在当前mtx上的线程去抢占锁,让后继续执行:
void fun()
{
while (true)
{
mtx.lock();
std::cout << "thread_id = " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}