关于多线程中抛出错误的有关问题

关于多线程中抛出异常的问题

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_errorusing namespace std;

std::mutex mtx;

void print_even(int x) {
printf("%d thread id is %d\n", x, this_thread::get_id());
// std::lock_guard<std::mutex> lck(mtx);
if (x % 2 == 0) printf("%d is even\n", x);
else throw (std::logic_error("not even"));
}


int main()
{
std::thread threads[10];

for (int i = 0; i < 10; ++i) {
try {
threads[i] = std::thread(print_even, i);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
}

for (auto& th : threads) th.join();

cout << "Here\n";

return 0;
}


各位大神,请帮小弟看看为什么以上代码运行会报错退出? 谢谢
------解决思路----------------------
引用:
Quote: 引用:

线程中的throw屏蔽后再试试

去掉throw是可以运行的。这是为什么呢?
线程中无法抛出异常给主线程吗?


没有办法try到,可以试试SetUnhandledExceptionFilter
------解决思路----------------------
1. 不要混用std::printf和std::cout
2. std::cout 用std::endl 而不用"\n"
3. ..........小错误太多了, 
4. 试试c++11的异常指针

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_errorusing namespace std;


std::mutex mtx;

void print_even(int x, std::exception_ptr* ptr) {
    try {
        std::lock_guard<std::mutex> lck(mtx);
        std::cout << x << "thread id is " << std::this_thread::get_id() << std::endl;
        if (x % 2 == 0)std::cout << x << "is even" << std::endl;
        else throw (std::logic_error("not even"));
    }
    catch (...) {
        *ptr = std::current_exception();
    }
}


int main() {
    struct {
        std::exception_ptr  teptr = nullptr;
        std::thread         thread;
    } data[10];
    for (auto& d : data) {
        d.thread= std::thread(print_even, int(&d - data), &d.teptr);
    }
    for (auto& d : data) {
        d.thread.join();
        if (d.teptr) {
            try {
                std::rethrow_exception(d.teptr);
            }
            catch (std::logic_error&) {
                std::lock_guard<std::mutex> lck(mtx);
                std::cout << "[exception caught]" << std::endl;
            }
        }
    }
    std::cout << "Here" << std::endl;

    return 0;
}

------解决思路----------------------
线程中的异常要在线程中接收。。没法抛给主线程。