在 while 循环中的另一个线程内的线程 [英] Thread inside another thread in a while loop

查看:66
本文介绍了在 while 循环中的另一个线程内的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 还很陌生,我现在正在试验线程.我正在尝试在 while 循环下的线程内创建一个线程.但我认为它似乎不起作用.目前我的代码如下所示:

I'm pretty new to C++ and I'm experimenting with threads right now. I'm trying to create a thread inside a thread under a while loop. But I don't think it seems to be working. Presently my code looks like this:

#include <>
std::vector<pthread_t> outer_thread, inner_thread;

    void *inner_thread(void *ptr)
    {
      string data1;
      data1 = *(reinterpret_cast<string*>(ptr));
      cout << "inner thread started " << data1;

/* do something */
      cout << "inner thread stopped " << data1;

pthread_exit(NULL);
  return 0;


    }

    void *outer_thread(void *ptr )
    {
cout << "out thread started" << endl;
//cout << ptr << endl;
//cout << *(reinterpret_cast<string*>(ptr)) << endl;
string data;
data = *(reinterpret_cast<string*>(ptr));


      string str3;
while (getline(data,str3))
{
      cout << "out thread started" << endl;


pthread_t in_thread;
in_vec.push_back(str3);
                int create_thread2 = pthread_create(&in_thread, NULL, &inner_thread, reinterpret_cast<void*>(&(in_vec.at(j))));
                inner_thread.push_back(in_thread);


      if (create_thread2 != 0) 
        cout << "Error : Thread";


      j++;

      cout << "out thread ends " << j << create_thread2 << endl ;

    }
         for (int k = 0; k < j ; k++)

{
pthread_join(inner_thread.at(k),NULL) ;
}

pthread_exit(NULL);
  return 0;

}   
    int main (int argc, char *argv[])
    {
      int i = 0;
      while (getline(gin,str))
      {
 string str1;
                pthread_t out_thread;
                cout << "str1" << str1 << endl;
now_vec.push_back(str1);
int create_thread = pthread_create(&out_thread, NULL, &outer_thread, reinterpret_cast<void*>(&(now_vec.at(i))));
                outer_thread.push_back(out_thread);
                if (create_thread != 0) cout << "Error : Thread" ;

        i++;
      }

for (int k = 0 ; k < i; k ++)
{
cout << i << endl;
//cout << "third thread " << outer_thread.at(1) << endl;
cout << outer_thread.at(k) << endl;
cout << "out out out" << endl;
pthread_join(outer_thread.at(k),NULL) ;
}


    }

我正在尝试读取一个包含应该读取的文件列表的文件.我想同时阅读所有这些文件.所有这些文件都包含信息,需要另一组线程来启动另一个操作.所以这也需要同时进行.这就是我运行 2 组线程的原因.让我知道是否有更快更简单的方法来做到这一点?

I'm trying to read a file which contains the list of files that should be read. I want to read all these files simultaneously. All these files contain information and needs another set of threads to start another operation. So this also needs to be done simultaneously. That's the reason I have 2 sets of threads running. Let me know If there is any faster and simpler way to do this?

好像要等到内线程结束再开始下一次迭代.我希望内线程在外线程内同时运行.我可以知道该怎么做吗?

It seems to wait till the inner thread finishes and then starts with the next iteration. I want the inner threads to run simultaneously inside the outer thread. May I know how to go about this?

推荐答案

您对线程操作的看法是错误的.一个线程不在另一个线程内运行.它们是同一进程内的独立执行流,它们的共存是平面的,而不是分层的.

Your view of the operation of threads is wrong. A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical.

使用多线程时要遵循的一些简单规则:

Some simple rules to follow when working with multiple threads:

  • 创建线程的开销很大,因此请避免快速创建和销毁它们.最好在应用程序启动时创建一次线程,并在工作可用时为它们分配工作.
  • 在进行计算工作时,请避免创建多于 CPU 上可以同时执行的线程数.任何额外的线程都会导致过多的上下文切换并降低您的应用程序的速度.
  • 尽可能避免使用共享资源,如果数据结构必须在线程之间共享,请尝试寻找无锁实现.如果您的共享资源在无锁实现中不可用,则使用锁来保护它,但要非常小心,锁的不当使用可能导致您的应用程序死锁或您的应用程序性能降级到串行执行情况(好像有只有一个线程).

在您的特定情况下,如果您想通过并行处理多个文件来加速它们的处理(并假设这些线程需要完成的唯一任务是处理这些文件),那么可能的解决方案如下:

In your particular case, if you want to speed up the processing of multiple files by processing them in parallel (and assuming the only task these threads need to achieve is the processing of these files), then a possible solution would look like:

  1. 读入要操作的文件列表
  2. 将列表分成几个部分(CPU 上的每个逻辑处理器一个部分).
  3. 创建您的工作线程(每个逻辑处理器一个),传入文件列表的一部分(不要尝试在创建它的同一个循环中加入线程,这将阻塞,直到线程完成执行,导致您的应用程序串行执行而不是并行执行,这是您提供的示例代码中的情况)

工作线程可以遍历它们的文件列表,一次读取一个并处理它们.

The worker threads can loop over their list of files, reading them one at a time and processing them.

与您提出的解决方案相反,此解决方案不会为每个文件创建一个线程.相反,它会创建尽可能多的线程在您的 CPU 上并行运行,从而避免过度的上下文切换.

In contrast to you proposed solution this one will not create a thread per file. Instead it will create as many threads as can run in parallel on your CPU avoiding the excessive context switching.

上面的一个原始例子:

#include <pthread.h>
#include <vector>
#include <string>

#define NUM_THREADS 4

std::vector<std::string> work_pool[NUM_THREADS];

void *worker_thread(void *args);

int main(int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];

    // Read list of files here, distribute them evenly amongst the work_pools

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, worker_thread, (void *)i);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

void *worker_thread(void *args)
{
    const int id = (int)args;
    std::vector<std::string>::iterator it;

    for (it = work_pool[id].begin(); it != work_pool[id].end(); it++) {
        // Read file and process it here
    }

    return NULL;
}

这篇关于在 while 循环中的另一个线程内的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆