【问题标题】:Tree Traversal with 2 threads, printing node data simultaneously2个线程的树遍历,同时打印节点数据
【发布时间】:2021-12-29 17:05:41
【问题描述】:

我们有两个执行前序遍历的线程。我们必须为以下示例树打印数据:

           1
        /     \
       2       3
      / \     / \
     4  NULL NULL NULL
    / \
 NULL NULL

...输出为:1 1 2 2 4 4 3 3

这里第一个“thread1”应该打印一个值,然后“thread2”应该打印一个值。

【问题讨论】:

  • 你有什么问题?

标签: multithreading tree


【解决方案1】:

以下是可能的解决方案之一,是否还有其他优化解决方案:

#include <iostream>
#include <bits/stdc++.h>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

bool ready1 = false;
bool ready2 = false;
mutex m;
condition_variable cond;

typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
 
    Node(int val)
    {
        data = val;
        left = NULL;
        right = NULL;
    }
} Node;

void prod1(Node *root) {
        if (root == NULL) {
            return;
        }
        unique_lock<mutex> lock(m);
        cond.wait(lock, [](){
            return ready1;
        });
        cout<<std::this_thread::get_id()<<" "<<root->data<<endl;
        ready2 = true;
        ready1 = false;
        lock.unlock();
        cond.notify_one();
        prod1(root->left);
        prod1(root->right);
    
}

void prod2(Node *root) {
        if (root == NULL) {
            return;
        }
        unique_lock<mutex> lock(m);
        cond.wait(lock, [](){
            return ready2;
        });
        cout<<std::this_thread::get_id()<<" "<<root->data<<endl;
        ready1 = true;
        ready2 = false;
        lock.unlock();
        cond.notify_one();
        prod2(root->left);
        prod2(root->right);
    
}
 
int main()
{
    /*create root*/
    struct Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    /* 4 becomes left child of 2
               1
            /     \
           2       3
          / \     / \
         4  NULL NULL NULL
        / \
     NULL NULL
    */
    thread t1(prod1, root);
    thread t2(prod2, root);
     {
        std::lock_guard<std::mutex> lk(m);
        ready1 = true;
       // std::cout << "main() signals data ready for processing\n";
    }
    t1.join();
    t2.join();
    //preorder(root);
    
    return 0;
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • “还有其他优化方案吗”:回答部分不应该用于提问。如果这是您的主要问题,请编辑您的问题并将其添加到其中。那么至少你的问题将是一个question,这是目前所缺乏的。
猜你喜欢
  • 2012-09-23
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多