小编sta*_*son的帖子

C++ 11 std :: thread join在Xcode 6上遇到system_error异常和SIGABRT崩溃?

这是一个简单的线程跟踪程序.线程只打印前十个整数,然后打印"线程完成"消息.

#include <iostream>
#include <vector>
#include <numeric>
#include <thread>

void f();

int main(int argc, const char * argv[]) {
    std::thread t(f);

    std::cout << "Thread start" << std::endl;

    t.detach();
    t.join();

    std::cout << "Thread end" << std::endl;

    return 0;
}

void f()
{
    std::vector<int> a(10);
    std::iota(a.begin(), a.end(), 0);

    for(const int& i : a)
    {
        std::cout << i << std:: endl;
    }
    std::cout << "Thread is done." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,当它运行时,t.join会在libc ABI中的某处抛出一个std :: __ 1 :: system_error异常,导致程序以SIGABRT终止:

Thread start
0
1
2
3 …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading sigabrt c++11

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

在C/C++中将数据从一个文件复制到另一个文件的最快方法?

在我的代码中,我有一种情况需要将数据从一个文件复制到另一个文件.我想出的解决方案如下:

const int BUF_SIZE = 1024;
char buf[BUF_SIZE];

int left_to_copy = toCopy;
while(left_to_copy > BUF_SIZE)
{
    fread(buf, BUF_SIZE, 1, fin);
    fwrite(buf, BUF_SIZE, 1, fout);
    left_to_copy -= BUF_SIZE;
}

fread(buf, left_to_copy, 1, fin);
fwrite(buf, left_to_copy, 1, fout);
Run Code Online (Sandbox Code Playgroud)

我的主要想法是可能有类似memcpy的东西,但是对于文件中的数据.我只给它两个文件流和总字节数.我搜索了一下,但我找不到任何这样的东西.

但是如果没有这样的东西,我应该使用什么缓冲区大小来实现最快的传输?更大意味着更少的系统调用,但我认为它可能会破坏系统上的其他缓冲或缓存.我应该动态分配缓冲区,以便只进行一对读/写调用吗?在这种特定情况下,典型的传输大小是从几KB到十几MB.

编辑:对于操作系统特定信息,我们使用的是Linux.

EDIT2:

我尝试使用sendfile,但它没有用.它似乎写了适量的数据,但它是垃圾.

我用上面这样的东西替换了我的例子:

fflush(fin);
fflush(fout);
off_t offset = ftello64(fin);
sendfile(fileno(fout), fileno(fin), &offset, toCopy);
fseeko64(fin, offset, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

我添加了flush,offest,并且一次寻找一个,因为它似乎没有工作.

c c++ file-io fwrite fread

3
推荐指数
1
解决办法
7470
查看次数

从模板化容器类型获取元素类型

我正在尝试编写一个模板函数,该函数采用具有任意数字类型的任意容器类:

template <typename NumType, typename ContType>
double avg_nums(const ContType<NumType> & data)
{
    double sum = 0;

    for(ContType::const_iterator iter = data.cbegin(); iter != data.cend(); ++iter)
    {
        if(typeid(NumType) == typeid(char) || typeid(NumType) == typeid(unsigned char))
        {
            std::cout << static_cast<int>(*iter) << std::endl;
        }
        else
        {
            std::cout << *iter << " ";
        }

        sum += *iter;
    }
    std::cout << std::endl;

    return sum  / data.size();
}
Run Code Online (Sandbox Code Playgroud)

但这会产生语法错误(VS2012)。这也不起作用:

template <typename NumType, typename ContType<NumType> >
double avg_nums(ContType<NumType> & data)
Run Code Online (Sandbox Code Playgroud)

我希望容器中的对象类型是模板参数以及容器类型,这样我就可以添加对 NumType 的特定情况的检查。如果我将函数签名更改为

template <typename NumType, typename ContType> …
Run Code Online (Sandbox Code Playgroud)

c++ templates stl

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

标签 统计

c++ ×3

c ×1

c++11 ×1

file-io ×1

fread ×1

fwrite ×1

multithreading ×1

sigabrt ×1

stl ×1

templates ×1