台州永建建设有限公司网站,wordpress loading,蜂鸟摄影网官网,重庆万州网站建设公司电话实验 简介#xff1a;我们启动并行启动两个线程#xff0c;但设置一个全局互斥锁#xff0c;在两个线程中等待并占用互斥锁#xff0c;然后输出日志。 代码 #include iostream
#include thread /* C 多线程库 */
#include mutex …实验 简介我们启动并行启动两个线程但设置一个全局互斥锁在两个线程中等待并占用互斥锁然后输出日志。 代码 #include iostream
#include thread /* C 多线程库 */
#include mutex /* C 互斥锁 *//* 定义一个全局锁子 */
std::mutex mt;/* 定义线程1 */
void thread_1()
{/* 等待其他程序将这个锁解开并以当前程序名义上锁 在程序结束时自动解锁*/std::lock_guardstd::mutex guard(mt);for(int i10; i 0 ; i--){std::cout thread 1 , i i std::endl;std::this_thread::sleep_for(std::chrono::microseconds(100));}std::cout thread_1 end. std::endl;
}/* 定义线程2 */
void thread_2()
{/* 等待其他程序将这个锁解开并以当前程序名义上锁 在程序结束时自动解锁*/std::lock_guardstd::mutex guard(mt);for(int i10; i 0 ; i--){std::cout thread 2 , i i std::endl;std::this_thread::sleep_for(std::chrono::microseconds(100));} std::cout thread_2 end. std::endl; }int main(int argc, char const *argv[])
{std::cout -------------------------------- std::endl;/* 启动两个线程并行执行函数注意这里已经开始运行了两个函数 */std::thread t1(thread_1);std::thread t2(thread_2);/* 阻塞等待线程的结束标志 */t1.join();t2.join();std::this_thread::sleep_for(std::chrono::seconds(20));std::cout -------------------------------- std::endl;return 0;
} 实验结果上述代码执行结果 如果注释等待并占用互斥锁实验结果如下