2014-03-02 35 views
0

您好,我在運行此腳本時出錯。它使用多線程,並在類中有數組。例如,我試圖設置數組,並使用foo1foo做一個while (gg[50] != 40) do xxxxxx從C++中的類訪問數組內容時出錯

我有一個cout來驗證數組已設置,但它返回垃圾,但當我問在主,它返回正確。有沒有解決這個問題?或者有沒有更好的方法在Windows中做到這一點?

#include "stdafx.h" 
#include <thread> 
#include <iostream> 
#include <stdio.h>  /* printf */ 
#include <time.h>  /* clock_t, clock, CLOCKS_PER_SEC */ 

using namespace std; 

class bar { 
public: 

void setarray(int r, double y){ 
    gg[r] = y; 
} 


void foo() { 
    int y = 0; 
    cout << gg[50] << "gg2" << endl; 
    std::cout << "hello from member function2" << std::endl; 
    while (gg[50] != 40){ 
     y++; 
    } 
    cout << y << " y2" << endl; 
} 

void foo1() { 
    int y = 0; 
    std::cout << "hello from member functiondddw1" << std::endl; 

    cout << gg[50]<< "gg1"<<endl; 
    std::thread(&bar::foo, bar()).detach(); 

    while (gg[50] != 40){ 
     y++; 
    } 
    cout << y << " y1" << endl; 

} 

double getarray(int g){ 
    double ek = gg[g]; 
    return ek; 
} 
private: 
double gg[80]; 

}; 

int main() 
{ 

bar jj; 

int u=0; 
cout << "which array" << endl; 
cin >> u; 
double dd=0; 
cout << "which number" << endl; 
cin >> dd; 
    jj.setarray(u, dd); 
    if(jj.getarray(u) == 3){ 
    clock_t tt; 
    tt = clock(); 

    std::thread(&bar::foo1, bar()).detach(); 
    tt = clock() - tt; 

    printf("It took me %d clicks (%f seconds).\n", tt, ((float)tt)/  CLOCKS_PER_SEC); 

    cout << "done" << endl; 
     } 
    cout << jj.getarray(50); 
    u=0; 
    cout << "which array" << endl; 
    cin >> u; 
dd=0; 
    cout << "which number" << endl; 
    cin >> dd; 
    jj.setarray(u, dd); 

cin.get(); 
return 0; 
} 

回答

0

從cout打印垃圾到確認垃圾時,您的描述如此不清楚。但是,如果從線程引用cout,問題是main()不會等到線程完成並實際退出並銷燬Bar jj實例。這就是垃圾可能被打印的原因。最佳實踐規則 - 主要應等待其所有線程完成,然後才能返回。

+0

感謝您的回答我已經嘗試過您的答案,但仍然沒有..我在調用任何線程之前分配gg [50],因此加入/分離不應該發揮作用AFAIK – user3370016

0

我找到了一些重寫的​​解決方案。我加

void main2() 
{ 
    std::thread(&bar::foo1, this).detach(); 
} 

並從main調用它並添加。 std :: thread(& bar :: foo,this).detach(); 到其他功能。