簡體   English   中英

c ++ pthread_create返回值

[英]c++ pthread_create returning value

我正在嘗試對二進制樹的順序遍歷進行多線程處理。 由於pthread_create,我收到錯誤。

    #include <iostream>
    #include <pthread.h>
    #include <list>

    using namespace std;


    static pthread_t threads[9];
    static int count=0;


    struct node
    {
    int value=0;
    node *left=NULL;
    node *right=NULL;
    };

    list<int> inordertraversal(node* n)
    {

    list<int> l1,l2;

    if(n->left!=NULL)
    list<int> l1=pthread_create(&threads[count++],NULL,inordertraversal,n->left);

    if(n->right!=NULL)
    list<int> l2=pthread_create(&threads[count++],NULL,inordertraversal,n->right);

    list<int> l;
    l.insert(l.begin(),l1.begin(),l1.end());
    l.push_back(n->value);
    l.insert(l.end()--,l2.begin(),l2.end());

    return l;

    }


    struct node* newNode(int data)
    {

    node* node;
    node->value=data;
    node->left=NULL;
    node->right=NULL;
    return node;

    }




    int main()
    {

     struct node *root=newNode(7);
     root->left=newNode(9);
     root->right=newNode(5);
     root->left->left=newNode(13);
     root->left->right=newNode(17);
     root->right->left=newNode(56);
     root->right->right=newNode(21);
     root->left->left->left=newNode(45);
     root->right->left->right=newNode(45);
     root->left->left->right=newNode(67);

    list<int> l=inordertraversal(root);

    for(list<int>::iterator it=l.begin();it!=l.end();it++)
    {
    cout<<*it<<" ";
    }


    }

我想使用pthread_create從傳遞給線程的函數返回列表元素。 錯誤如下: -

/usr/include/pthread.h|244|error:初始化'int pthread_create的參數3(pthread_t *,const pthread_attr_t *,void *( )(void ),void *)'[-fpermissive] |

/home/dinu94/dummyspace/interview_prep/ThreadedBinaryTree/main.cpp|25|error:從'int'轉換為非標量類型'std :: list'

/home/dinu94/dummyspace/interview_prep/ThreadedBinaryTree/main.cpp|28|error:從'std :: list( )(node )'到'void *( )(void )的無效轉換'[-fpermissive] |

/usr/include/pthread.h|244|error:初始化'int pthread_create的參數3(pthread_t *,const pthread_attr_t *,void *( )(void ),void *)'[-fpermissive] |

/home/dinu94/dummyspace/interview_prep/ThreadedBinaryTree/main.cpp|28|error:從'int'轉換為非標量類型'std :: list'

我不知道該怎么辦。

編輯:如果pthread_create是錯誤的方法,返回值的替代方法是什么?

謝謝

pthread線程函數必須符合庫指定的函數定義:

int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)

所以,你的函數list<int> inordertraversal(node* n)不符合void* ()(void)

您必須將函數簽名更改為符合上述簽名的函數,然后以遞歸方式調用。

void* inorder(void)
{
    pthread_create(&threads[count++],NULL,wrapper,(void *)n->left);

}

list<int> l; 作為一個類成員,所以你不需要傳遞每個函數調用。

你誤解了pthread_create作用。 它只是創建線程並返回線程創建的狀態(它是否工作或失敗)。 它根本不處理線程中運行的函數返回的內容。 事實上,線程函數可能根本不應該返回結果。 它可能應該更新一些可供所有線程訪問的公共變量(此時需要使用互斥鎖或其他一些互斥機制)。

pthread_create需要一個函數指針,該函數指針的類型應為void *()(void *)。 您的函數有返回類型列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM