并行while循环而不使用线程
Parallell while loops without using threads
(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::future
和std::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
将阻塞,直到线程完成为止。但它们将并行运行。
在您的情况下,这取决于字符串/字母表的大小和算法,尽管我怀疑在多个线程中这样做会给您带来多大好处。线程开销可能比整个计算花费更长的时间,因此您应该衡量执行单线程操作是否更快。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- 为什么我不能在 while 循环中创建线程?
- 重新启动后,线程无法在 while 循环中再次运行
- 在 While 循环中重用对象的多线程
- 条件变量,在C++线程中具有 while 循环
- 如何将while循环的每一次迭代都分配给线程
- 即使使用另一个线程,启动while循环也会冻结程序
- 如何正确使用带有while循环的线程
- 如何停止包含while(1)的线程
- while循环中线程内部的另一个线程
- 当主应用程序处于while循环时,Boost线程未运行