zoukankan      html  css  js  c++  java
  • C++11 thread

    #include <thread>
    #include <iostream>
    #include <mutex>
    using namespace std;
    
    int k = 200;
    mutex mt;
    void f1(){
    	while (true){
    		mt.lock();
    		if (k > 0){
    			k--;
    			cout << "f1:" << k << endl;
    		}else{
    		// 如果中途退出,一定要释放锁,防止出现独占式情况
    			mt.unlock();
    			break;
    		}
    		mt.unlock();	
    	}
    	
    	
    }
    
    void f2(){
    
    	while (true){	
    		mt.lock();
    		if (k > 0){
    			k--;
    			cout << "f2:" << k << endl;
    		}else{
    		// 如果中途退出,一定要释放锁,防止出现独占式情况
    			mt.unlock();
    			break;
    		}
    		mt.unlock();
    	}
    	
    
    }
    int main(){
    	thread t1(f1);
    	thread t2(f2);
    	t1.join();
    	t2.join();
    	return 0;
    }
    

    • join()
        join用于阻塞当前线程等待thread执行完执行体。一般用于多线程之间进行同步。对于不具备分离属性的线程必须要join,否则会导致terminal。我觉得白话文就是join 是让当前主线程等待所有的子线程执行完,才能退出。

    • joinable()
        成员函数joinable用于检测thread是否需要join。joinable为false的情况有3种:1.thread调用过detach; 2.thread已经join过; 3.thread为空。

  • 相关阅读:
    112.路径总和
    二叉树的中序遍历
    HTML基础及案例
    web概念概述
    Spring JDBC
    数据库连接池
    JDBC连接池&JDBCTemplate
    JDBC
    MySQL多表&事务
    DCL
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537751.html
Copyright © 2011-2022 走看看