如何使用多线程的Lambda表达式?

时间:2015-02-07 03:44:30

标签: c++ multithreading lambda

有一个函数auto check = [](void * threadIn)->bool。 我试图创建3个工作线程,每个线程用参数check执行int i并返回布尔结果。

我排除了多线程之外的部分代码。如果三个线程的返回结果为真,我想将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 thread的组合。

有人可以帮我解决这个问题吗?感谢。

1 个答案:

答案 0 :(得分: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 * )表达此程序可能更容易,它包含真实函数并进行转换。