需要帮助识别简单多线程代码中的错误
Need Help Identifying Bug in Simple Multithreaded Code
我试图解决这里给出的问题 - https://leetcode.com/problems/print-foobar-alternately/。
我编写了以下代码来解决问题,但它超过了分配的时间限制。我不明白为什么会这样。有人可以指出我的错误吗?另外,我如何更正下面给出的代码,使其在仅使用 while 循环充当互斥锁时执行得更快?
class FooBar {
private:
int n;
int state = 0;
public:
FooBar(int n) {
this->n = n;
state = 0;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
// printFoo() outputs "foo". Do not change or remove this line.
while(state == 1);
printFoo();
state = 1;
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
// printBar() outputs "bar". Do not change or remove this line.
while(state == 0);
printBar();
state = 0;
}
}
};
虽然循环不是锁。锁只允许一个线程通过。在你的代码中,如果 state=0,两个线程可能会一个接一个地打印 foo。要解决此问题,请使用互斥锁和唯一锁。
for (int i = 0; i < n; i++) {
// printFoo() outputs "foo". Do not change or remove this line.
while(state==1);
unique_lock<mutex> lck(m1); //Make mutex m1 as a global mutex
printFoo();
state = 1;
}
切勿跨线程读取相同的变量,除非将其设置为原子或修改锁中的变量。在此示例中,由于值状态在共享互斥锁中正在更改,因此无需使用原子。
相关文章:
- 将鼠标悬停在问题上时与预期">"相关的代码错误
- VI工作室代码错误无法打开输出文件主.exe
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 有关矩阵的代码错误导致分段错误(内核转储)
- C++ Schannel POST 400 错误代码错误请求
- Java 本机访问代码错误:"Invalid memory access"
- 代码错误修改
- C++代码错误分配
- "_FCbuild"不能用作函数 - C/C++ 代码错误
- 我的代码错误类型警告 1 警告 C4018 和更多错误
- 代码错误(从 1 到 100 找到质数)
- OpenCV VisualStudio,C 代码错误尝试访问像素
- 当我使用的教程完全没有错误时,为什么我的代码错误
- 简单的NOOB C 输入/输出问题:代码错误
- 为什么enumProcessModules返回false值和299代码错误
- WinhttpSetoption()失败设置TLSV1.2,带有错误代码错误_internet_incorrect_ha
- 苹果安全传输代码错误
- C++ - 国际象棋主教移动代码错误
- 导入Python库时,嵌入了Python代码错误
- 编译提升C 代码错误