并行while循环而不使用线程

Parallell while loops without using threads

本文关键字:线程 while 循环 并行      更新时间:2023-10-16

(C++(有没有可能在不使用线程的情况下运行两个并行while循环?我试着把它们一个接一个地放在一个for循环中,但这对我来说不起作用,因为我在while condition中使用的变量在第一个循环中发生了变化,我需要它对两个循环都是相同的。这是代码:

for (size_t j = 0; j < word.length(); j++)
{       
    while (word[j] != tmp->data)
    {
        counter1++;
        tmp = tmp->next;
    }
    while (word[j] != tmp->data)
    {
        counter2++;
        tmp = tmp->previous;
    }       
}

来自注释:

我从一个字符串中提取字母,并试图找出哪条路径更短,才能到达字母表中的同一个字母,向前还是向后。我使用的是循环双链表。

听起来你只想要一个带有两个tmp指针的while循环:

for (size_t j = 0; j < word.length(); j++)
{       
    while (word[j] != tmp1->data && word[j] != tmp2->data)
    {
        counter++;
        tmp1 = tmp1->next;
        tmp2 = tmp2->previous;
    }       
}

没有线程,这是不可能的(或者你可以使用进程间,但我想这不是你的重点(

使用std::futurestd::async 可以避免使用"手动"线程

你可以让每个搜索都有这样的功能:

int forward(std::string word)
{
  int counter = 0;
  for (size_t j = 0; j < word.length(); j++)
  {       
      while (word[j] != tmp->data)
      {
          counter++;
          tmp = tmp->next;
      }    
  }
  return counter;
}

或相应的backwards

然后这样称呼他们。

std::string word = //....
auto res1 = std::async(std::launch::async, forward,word);
auto res2 = std::async(std::launch::async, forward,word);
//do whatever....
int counter1 = res1.get(); //get the result
int counter2 = res2.get();  

但请注意,get将阻塞,直到线程完成为止。但它们将并行运行。

在您的情况下,这取决于字符串/字母表的大小和算法,尽管我怀疑在多个线程中这样做会给您带来多大好处。线程开销可能比整个计算花费更长的时间,因此您应该衡量执行单线程操作是否更快。