基本同步原语-安全吗? [英] Primitive synchronization primitives -- safe?

查看:79
本文介绍了基本同步原语-安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在受限制的设备上,我经常发现自己在2个线程和2个布尔值之间伪造"了锁.每个线程只能由一个线程读取,而只能由另一个线程写入.这就是我的意思:

On constrained devices, I often find myself "faking" locks between 2 threads with 2 bools. Each is only read by one thread, and only written by the other. Here's what I mean:

bool quitted = false, paused = false;
bool should_quit = false, should_pause = false;

void downloader_thread() {
    quitted = false;
    while(!should_quit) {
        fill_buffer(bfr);
        if(should_pause) {
            is_paused = true;
            while(should_pause) sleep(50);
            is_paused = false;
        }
    }
    quitted = true;
}

void ui_thread() {
    // new Thread(downloader_thread).start();
    // ...
    should_pause = true;
    while(!is_paused) sleep(50);
        // resize buffer or something else non-thread-safe
    should_pause = false;
}

当然,在PC上我不会这样做,但是在受约束的设备上,读取bool值似乎比获取锁快得多.当然,当需要更改缓冲区时,我会权衡恢复速度较慢(请参见"sleep(50)").

Of course on a PC I wouldn't do this, but on constrained devices, it seems reading a bool value would be much quicker than obtaining a lock. Of course I trade off for slower recovery (see "sleep(50)") when a change to the buffer is needed.

问题-它是完全线程安全的吗?还是在伪造这样的锁时需要注意一些隐藏的陷阱?还是我根本不应该这样做?

The question -- is it completely thread-safe? Or are there hidden gotchas I need to be aware of when faking locks like this? Or should I not do this at all?

推荐答案

除非您详细了解设备的内存架构以及编译器生成的代码,否则该代码并不安全.

Unless you understand the memory architecture of your device in detail, as well as the code generated by your compiler, this code is not safe.

仅仅因为它似乎可以工作,并不意味着它会工作.像无约束类型一样,受约束"设备正变得越来越强大.例如,我不会反对在手机中找到双核CPU.那意味着我不会打赌上面的代码会起作用.

Just because it seems that it would work, doesn't mean that it will. "Constrained" devices, like the unconstrained type, are getting more and more powerful. I wouldn't bet against finding a dual-core CPU in a cell phone, for instance. That means I wouldn't bet that the above code would work.

这篇关于基本同步原语-安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆