c++使用mutex为函数上锁

#ifndef HOROVOD_COMMON_H
#define HOROVOD_COMMON_H

#include<string.h>
#include <string>
#include<iostream>
#include<memory>
//#inlcude<cstring>
using namespace std;

typedef unsigned int byte; 
void getdefine(int a){
#if defined(_MSC_VER)
#define FLATBUFFERS_BYTESWAP16 int
#else
     #if defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ < 408
     #define FLATBUFFERS_BYTESWAP17 int
    #endif

#endif

cout<<"this is getdefine";
FLATBUFFERS_BYTESWAP16 k=9;

}

#if defined HOROVOD_COMMON_H
#define FLATBUFFERS_BYTESWAP32 string

#endif
enum MPIDataType:byte {
    HOROVOD_UINT8 = 0,
    HOROVOD_INT8 = 1,
    HOROVOD_UINT16 = 2,
    HOROVOD_INT16 = 3,
    HOROVOD_INT32 = 4,
    HOROVOD_INT64 = 5,
    HOROVOD_FLOAT32 = 6,
    HOROVOD_FLOAT64 = 7,
    HOROVOD_BOOL = 8
};
typedef unsigned __int32 uint32_t;
string & ParseFromString(std::string& input){

    cout<<"ParseFrom String:";
    cout<<input<<endl;
    *(&input)="xq";
    return *&input;
}
class From2{
public:
 const void getnum() {
    //F="qw";
    //const string x="horovod";
    F="wq";
     cout<<"getnum"<<endl;
}
private:
    string F;
};
void foo(int * d)  
{  
       cout<<"1234"<<endl;  
} 


class EnumTest{

public:
    enum EnumType
    {
        ALL=0,REDUCE=1
    };

};

#include<map>
#include<string>
#include<chrono>
#include<thread>
#include<mutex>
std::map<std::string,std::string> g_pages;
std::mutex g_pages_mutex;

using namespace std;
int number=0;
void save_page(const std::string & url){
    g_pages_mutex.lock();
    std::this_thread::sleep_for(std::chrono::seconds(2));   
    cout<<"sleep time is end! thread is["<<++number<<"]"<<endl;
    string result="fake content";
    g_pages[url]=result+url;
    g_pages_mutex.unlock();

}
int main(){

    thread t1(save_page,"first1");
    thread t2(save_page,"first2");
    if(t1.joinable()){
        t1.join();
        t2.join();
        cout<<"T1 join the main !"<<endl;

    }

    g_pages_mutex.lock();

    for(const auto &x:g_pages){
        cout<<x.first<<" "<<x.second<<endl;
    }

    g_pages_mutex.unlock();
return 0;
}


#endif

输出结果:

sleep time is end! thread is[1]
sleep time is end! thread is[2]
T1 join the main !
first1 fake contentfi
first2 fake contentfi
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/th_num/article/details/81063432