mercredi 14 septembre 2016

Local Static variable initialization is thread safe

Suppose I have a class with three static functions like this --

#include <vector>
#include <iostream>
using namespace std;
#include <thread>


class Employee
{

};

class client
{

public:
    void Doprocessing()
    {
        //is this thread safe in c++11/14
        static int i = CreateEmployee();

        //does it look good to use static variable like this to make it thread safe?
        static int k = ProcessEmploye();
    }

private:


    static int CreateEmployee()
    {
        static Employee * e = new Employee();
        InsertEmployee(e);
        return 1;
    }

    static int  InsertEmployee(Employee *e)
    {
        vec.push_back(e);
        return 1;
    }

    static int ProcessEmploye()
    {
        Employee* e = vec[0];
        //do something with e
        //...
        //.
        //Suppose 10 -20 lines 
        return 1;
    }


    static std::vector<Employee*> vec;
};

std::vector<Employee*> client::vec;

void func()
{
    client cobj;
    cobj.Doprocessing();
}

const int No_Of_Threads = 10;
int main() {


    std::thread * threadpointer = new std::thread[No_Of_Threads];

    std::srand(11);
    for (int i = 0; i < No_Of_Threads; i++)
    {
        threadpointer[i] = std::thread(func);
    }

    for (int i = 0; i < No_Of_Threads; i++)
    {
        threadpointer[i].join();
    }
    delete[] threadpointer;

    std::cout << " Good" << std::endl;
    return 0;
}

My question are -
1)If i use static int i = Somefunc() and no matter how bulky somefunc is, it will be called once and it will be thread safe ?
2) if answer of 1) is yes, Does it look good to programers eyes to use static int i = SomeFunc() for above purpose.

Aucun commentaire:

Enregistrer un commentaire