admin管理员组

文章数量:1599734

std::mutex mutex;
std::condition_variable cv;

// 条件变量与临界区有关,用来获取和释放一个锁,因此通常会和mutex联用。
std::unique_lock lock(mutex);
// 此处会释放lock,然后在cv上等待,直到其它线程通过cv.notify_xxx来唤醒当前线程,cv被唤醒后会再次对lock进行上锁,然后wait函数才会返回。
// wait返回后可以安全的使用mutex保护的临界区内的数据。此时mutex仍为上锁状态
cv.wait(lock)

上文摘自: C++11多线程-条件变量(std::condition_variable) - 简书前面我们介绍了线程(std::thread)和互斥量(std::mutex),互斥量是多线程间同时访问某一共享变量时,保证变量可被安全访问的手段。在多线程编程中,还有另一种十...https://www.jianshu/p/a31d4fb5594f

 之前总是纳闷,为什么明明对mutex进行unique锁定了,其他线程还能再次获取到该锁,进行后续的操作。上文对其进行很好的说明。

实际上wait函数已经进行了解释,只是没有消化了,通过上面链接,更好地进行了理解。

写了测试程序进行了验证

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#include <thread>
#include <mutex>
#include <condition_variable>

static std::mutex mtx;
static std::condition_variable cv;

void runthread(int index)
{
    std::unique_lock<std::mutex> lck(mtx);
    fprintf(stderr, "thread:%d is waiting.\n", index);
    cv.wait(lck);
    fprintf(stderr, "thread:%d is wakeup.\n", index);
}

int main()
{
    fprintf(stderr, "pid:%d\n", getpid());
    std::thread* pt[5];
    for (int i = 0; i < 5; i++)
    {
        pt[i] = new std::thread(runthread, i);
    }

    for (int i = 0; i < 30; i++)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        fprintf(stderr, "main thread sleep %d seconds\n", i);
    }

    cv.notify_all();

    for (int i = 0; i < 5; i++)
    {
        if (pt[i]->joinable())
        {
            pt[i]->join();
            delete pt[i];
            pt[i] = NULL;
        }
    }

    return 0;
}

执行的一次结果如下:

pid:8571
thread:0 is waiting.
thread:1 is waiting.
thread:4 is waiting.
thread:3 is waiting.
thread:2 is waiting.
main thread sleep 0 seconds
main thread sleep 1 seconds
main thread sleep 2 seconds
main thread sleep 3 seconds
main thread sleep 4 seconds
main thread sleep 5 seconds
main thread sleep 6 seconds
main thread sleep 7 seconds
main thread sleep 8 seconds
main thread sleep 9 seconds
main thread sleep 10 seconds
main thread sleep 11 seconds
main thread sleep 12 seconds
main thread sleep 13 seconds
main thread sleep 14 seconds
main thread sleep 15 seconds
main thread sleep 16 seconds
main thread sleep 17 seconds
main thread sleep 18 seconds
main thread sleep 19 seconds
main thread sleep 20 seconds
main thread sleep 21 seconds
main thread sleep 22 seconds
main thread sleep 23 seconds
main thread sleep 24 seconds
main thread sleep 25 seconds
main thread sleep 26 seconds
main thread sleep 27 seconds
main thread sleep 28 seconds
main thread sleep 29 seconds
thread:0 is wakeup.
thread:1 is wakeup.
thread:4 is wakeup.
thread:3 is wakeup.
thread:2 is wakeup.

写该测试程序的另外一个目的:确认使用mutex及condition_variable是否会增加进程的task数量(结果:不会增加)

[xxxx@localhost ~]$ ls /proc/8571/task/
8571  8572  8573  8574  8575  8576

本文标签: stdconditionvariableuniquelock