2015-02-07 27 views
0

有一個功能auto check = [](void * threadIn)->bool。 我試圖創建3個工作線程,每個線程都使用參數int i執行check並返回布爾結果。如何在多線程中使用Lambda表達式?

我排除了多線程之外的部分代碼。如果三個線程的返回結果爲真,我想將bool valid設置爲true。

這是我的代碼。

#include <iostream> 
#include <cstdlib> 
#include <pthread.h> 
#include <fstream> 
#include <string> 


#ifdef _WIN32 
# include <windows.h> 
#endif 

#ifdef linux 
# include <unistd.h> 
#endif 

using namespace std; 

int a[6][6]; 
#define forever for(;;) 

void main() 
{ 
forever 
{ 
    bool valid; 
    /* set input from file and set up the array */ 

    auto check = [](void * threadIn)->bool 
    { 
     bool flag=false; 
     int seq = * (int *) threadIn; 
     switch (seq){/*...*/} 
     return !flag; 
    }; 

    pthread_t threads[3]; 
    int rc; 
    int i, threadids[3]; 

    for (i = 0; i < 3; i++){ 
     threadids[i] = i; 
     cout << "main(): creating Thread " << i << endl; 
     rc = pthread_create(&threads[i], NULL, check, (void *)&threadids[i+1]); 
     if (rc){ 
      cout << "Error:unable to create thread," << rc << endl; 
      exit(-1); 
     } 
    } 
    cout << "main(): program exiting." << endl; 
    pthread_exit(NULL); 
    valid = (check(1) && check(2) && check(3)); 
} 
} 

有一些提到lambda表達式的錯誤消息。我不熟悉Lambda和Multi線程的組合。

任何人都可以幫我解決這個問題嗎?謝謝。

+2

爲什麼不使用'std :: thread'? – 2015-02-07 03:47:00

+3

「有一些提到lambda表達式的錯誤消息」 - 它們是超級祕密/只是眼睛,還是你認爲可能顯示錯誤*逐字*以及構建工具創建錯誤會對他有幫助? – WhozCraig 2015-02-07 03:50:45

回答

1
rc = pthread_create(&threads[i], NULL, check, (void *)&threadids[i+1]); 

pthread_create需要void * (*) (void *)類型的參數,所以參數類型和返回類型都是void *。你的lambda應該遵循這個簽名。

auto check = [](void * threadIn)-> void * 
{ 
    bool flag=false; 
    int seq = * (int *) threadIn; 
    switch (seq){/*...*/} 
    return reinterpret_cast< void * >(flag); 
}; 

另外,還有一些運行時錯誤。您可以通過鑄造創建序列號(它有效地做reinterpret_cast),但隨後提領恢復它們:

int seq = * (int *) threadIn; // Dereference of non-pointer 

這應該僅僅是相反的演員,因爲從來就沒有擺在首位真正的指針。

int seq = reinterpret_cast<int>(threadIn); // OK 

同樣,你需要使人們對所有的參數和返回值,以使最終的老本行:

valid = (check(1) && check(2) && check(3)); 

這可能是更容易表達使用普通功能bool valid(int)加上超載這一計劃extern "C" void * valid(void *)它包裝了真實的功能並進行演員表演。