小编Ary*_*yan的帖子

使用4个线程获取/释放语义

我目前正在阅读Anthony Williams的C++ Concurrency in Action.他的一个列表显示了这段代码,他声明z != 0可以解雇的断言.

#include <atomic>
#include <thread>
#include <assert.h>

std::atomic<bool> x,y;
std::atomic<int> z;

void write_x()
{
    x.store(true,std::memory_order_release);
}

void write_y()
{
    y.store(true,std::memory_order_release);
}

void read_x_then_y()
{
    while(!x.load(std::memory_order_acquire));
    if(y.load(std::memory_order_acquire))
        ++z;
}

void read_y_then_x()
{
    while(!y.load(std::memory_order_acquire));
    if(x.load(std::memory_order_acquire))
        ++z;
}

int main()
{
    x=false;
    y=false;
    z=0;
    std::thread a(write_x);
    std::thread b(write_y);
    std::thread c(read_x_then_y);
    std::thread d(read_y_then_x);
    a.join();
    b.join();
    c.join();
    d.join();
    assert(z.load()!=0);
}
Run Code Online (Sandbox Code Playgroud)

所以我能想到的不同执行路径是这样的:

1)

Thread a (x is now true)
Thread c (fails to increment z)
Thread b (y …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading memory-model memory-barriers stdatomic

19
推荐指数
2
解决办法
851
查看次数

模板类中的模板可变参数函数将无法编译

我正在尝试为模板类编写一个函数,该函数接受一个参数,该参数是大类私有数据中成员类的函数指针.当您调用该成员时,它会在较小的类上调用该函数.(令人困惑的权利?)为了证明,我在这里有一个非工作的例子:

#include <vector>
#include <iostream>

using namespace std;

template <typename T, typename C>
struct MyClass {

    template <typename F, typename... A>
    auto call_me(F func, A... args) { // pass in the function we want to call
        return (mContainer.*func) (args...); // call the function supplied by 
        // the parameter on the private member data
    }

    C mContainer; // this will be private in my actual code

};


int main() {
    MyClass<int, std::vector<int> > test;;

    cout << test.call_me(&std::vector<int>::size) << endl; // works …
Run Code Online (Sandbox Code Playgroud)

c++ templates member-function-pointers function-pointers variadic-templates

4
推荐指数
1
解决办法
75
查看次数