2014-02-12 36 views
0

下面的代码可能会产生未定义的行为吗?std :: thread未定义的行为

unsigned int total_threads = 10; 
vector<thread> t(total_threads); 
unsigned int *nums = (unsigned int*)calloc(total_threads, sizeof(int)); 

for(unsigned int i = 0; i < 1000; i++) 
{ 
    for(unsigned int j = 0; j < total_threads; j++) 
     t[j] = thread(func_, std::ref(nums[j])); 

    for(unsigned int j = 0; j < total_threads; j++) 
     t[j].join(); 

    for(unsigned int j = 0; j < total_threads; j++) 
    { 
     cout << nums[j] << " "; 
     nums[j] = 0; 
    } 
} 
+2

它取决于'func_'的功能。只要它修改了它给予的参考价值,我相当肯定这是完全明确的。 –

回答

4

是的,因为calloc可能会失败。检查返回值或使用std :: vector。

+0

为什么calloc可能失败?我的意思是,如果有剩余的可用内存,它可以失败吗? – Luka

+0

@Luka如果内存不能分配,就是一个例子。尽管如此,你的系统可能会决定不给你内存,所以你必须处理所有可能的返回值情况。 http://en.cppreference.com/w/cpp/memory/c/calloc –

+0

好点,但如果每件事都可以失败,那么如果我不能写入文件,如何报告错误?如果写入文件会失败怎么办? – Luka

相关问题