gpt4 book ai didi

c++ - 局部静态变量初始化是线程安全的

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:48 25 4
gpt4 key购买 nike

<分区>

假设我有一个包含三个静态函数的类:

#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;
}

我的问题是:
1) 如果我使用 static int i = Somefunc() 并且无论 somefunc 有多大,都将被调用一次 并且它是线程安全的吗?
2) 如果 1) 的答案是肯定的,那么为了上述目的使用 static int i = SomeFunc() 对程序员来说看起来不错吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com