gpt4 book ai didi

c++ - 在 C++11 中,使用 std::unique_lock 作为类成员是否明智(甚至安全)?如果是这样,是否有任何指导方针?

转载 作者:太空狗 更新时间:2023-10-29 20:21:54 28 4
gpt4 key购买 nike

将 std::unique_lock 用作类成员是否明智(甚至安全)?如果是这样,是否有任何指导方针?

我使用 std::unique_lock 的想法是确保在抛出异常的情况下解锁互斥量。

下面的代码给出了我当前如何使用 unique_lock 的示例。我想知道在项目增长太多之前我是否走错了方向。

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <unistd.h>


class WorkerClass {
private:
std::thread workerThread;
bool workerThreadRunning;
int workerThreadInterval;

int sharedResource;

std::mutex mutex;
std::unique_lock<std::mutex> workerMutex;

public:
WorkerClass() {
workerThreadRunning = false;
workerThreadInterval = 2;

sharedResource = 0;

workerMutex = std::unique_lock<std::mutex>(mutex);

unlockMutex();
}


~WorkerClass() {
stopWork();
}


void startWork() {
workerThreadRunning = true;
workerThread = std::thread(&WorkerClass::workerThreadMethod,
this);
}


void stopWork() {
lockMutex();
if (workerThreadRunning) {
workerThreadRunning = false;
unlockMutex();
workerThread.join();
}else {
unlockMutex();
}
}


void lockMutex() {
try {
workerMutex.lock();
}catch (std::system_error &error) {
std::cout << "Already locked" << std::endl;
}
}


void unlockMutex() {
try {
workerMutex.unlock();
}catch (std::system_error &error) {
std::cout << "Already unlocked" << std::endl;
}
}

int getSharedResource() {
int result;
lockMutex();
result = sharedResource;
unlockMutex();
return result;
}


void workerThreadMethod() {
bool isRunning = true;

while (isRunning) {
lockMutex();
sharedResource++;
std::cout << "WorkerThread: sharedResource = "
<< sharedResource << std::endl;
isRunning = workerThreadRunning;
unlockMutex();

sleep(workerThreadInterval);
}
}
};



int main(int argc, char *argv[]) {
int sharedResource;
WorkerClass *worker = new WorkerClass();

std::cout << "ThisThread: Starting work..." << std::endl;
worker->startWork();

for (int i = 0; i < 10; i++) {
sleep(1);

sharedResource = worker->getSharedResource();
std::cout << "ThisThread: sharedResource = "
<< sharedResource << std::endl;
}

worker->stopWork();

std::cout << "Done..." << std::endl;

return 0;
}

最佳答案

这其实很糟糕。将 std::unique_lockstd::lock_guard 存储为成员变量错过了作用域锁定和一般锁定的要点。

想法是在线程之间拥有共享锁,但每个线程都临时锁定锁保护的共享资源。包装器对象使其从函数返回安全且异常安全。

您首先应该考虑您的共享资源。在“ worker ”的背景下,我会想象一些任务队列。然后,该任务队列与某个锁相关联。每个工作人员使用 scoped-wrapper 锁定该锁以对任务进行排队或出队。只要工作线程的某个实例还活着,就没有真正的理由保持锁锁定,它应该在需要时锁定它。

关于c++ - 在 C++11 中,使用 std::unique_lock<std::mutex> 作为类成员是否明智(甚至安全)?如果是这样,是否有任何指导方针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665071/

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