尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

mutex互斥锁学习

mutex互斥锁学习 在C开发中使用多线程对同一个共享数据进行同时读写时如果没有任何同步保护措施就会产生数据竞争结果示定义数值错乱。那么如何避免这种现象呢答案就是使用互斥锁来解决这个问题。本篇就是学习互斥锁在多线程中的基本使用。下面是mutex的常用函数锁定lock锁定互斥体若互斥体不可用则阻塞(公开成员函数)try_lock尝试锁定互斥体若互斥体不可用则返回(公开成员函数)unlock解锁互斥体(公开成员函数)先来看一个不加锁的多线程同时读写数据的例子#include thread // std::thread #include mutex // std::mutex int g_count 0; //自增函数测试 void incrementation() { printf(incrementationstart\n); for (int i 0; i 1000000; i) { g_count; } printf(incrementationend\n); } int main() { std::thread t1(incrementation); std::thread t2(incrementation); t1.join(); t2.join(); //理论应该 2000000实际永远小于这个数 printf(g_count%d\n, g_count); return 0; }编译运行incrementation函数在两个线程中同时运行数据错乱正常结果应该是2000000但实际值是1267503。下面给这个函数加锁看g_count的值最终是多少。//mutex_lock_unlock.cpp mutex example #include thread // std::thread #include mutex // std::mutex //临界区互斥锁 std::mutex mtx; // mutex for critical section int g_count 0; //自增函数测试 void incrementation() { printf(incrementationstart lock\n); mtx.lock(); for (int i 0; i 1000000; i) { g_count; } //模拟耗时 std::this_thread::sleep_for(std::chrono::seconds(1)); //休眠1秒 printf(incrementationend lock\n); mtx.unlock(); } int main() { std::thread t1(incrementation); std::thread t2(incrementation); t1.join(); t2.join(); //理论应该 2000000不加锁实际永远小于这个数 printf(g_count%d\n, g_count); return 0; }运行结果加锁就是正常结果了。lock()以后一定要记得unlock(),这是配对的如果忘记unlock了那这个程序就只会显示前两行的打印了。try_lock()函数是指互斥锁没有加锁的时就给它加锁并返回true如果加锁了这个函数就返回false。下来来看具体的代码例子//mutex_try_lock.cpp mutex example //#include iostream // std::cout #include thread // std::thread #include mutex // std::mutex //锁定对g_count的访问 std::mutex mtx; // locks access to counter volatile int g_count 0; //非原子类型 void attempt_10k_incrementation() { printf(incrementationstart lock\n); for (int i 0; i 10000; i) { if (mtx.try_lock()) { // only increase if currently not locked: g_count; //仅在当前未被锁定时增加 mtx.unlock(); } } //模拟耗时 //std::this_thread::sleep_for(std::chrono::seconds(1)); //休眠1秒 printf(incrementationend lock\n); } int main() { std::thread threads[10]; //spawn 10 threads: 生成10个线程 for (int i 0; i 10; i) threads[i] std::thread(attempt_10k_incrementation); //join线程 for (auto th : threads) th.join(); printf(Possible output (any count between 1 and 100000 possible):\n); printf(%d successful increases of the counter.\n, g_count); return 0; }编译运行参考https://cplusplus.com/reference/mutex/mutex/https://zh.cppreference.com/cpp/thread/mutex
返回列表