c++ - 在 while 循环中将线程置于另一个线程中

标签 c++ multithreading while-loop

<分区>

我是 C++ 的新手,现在正在试验线程。 我正在尝试在 while 循环下的线程内创建一个线程。但我认为它似乎没有用。 目前我的代码如下所示:

#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 组线程的原因。 让我知道是否有更快更简单的方法来做到这一点?

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

最佳答案

你对线程运行的看法是错误的。一个线程不在另一个线程中运行。它们是同一进程中的独立执行流,它们的共存是扁平的,而不是分层的。

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

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

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

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

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

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

上面的一个原始例子:

#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;
}

关于c++ - 在 while 循环中将线程置于另一个线程中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24189298/

相关文章:

c++ - 为什么 std::list 有 remove 和 remove_if 函数

c++ - 浮点值不显示准确的位数 C++

c - 为什么“while(!feof(file))”总是错误的?

c++ - for 循环内的 while 循环

javascript - JavaScript 中 while 循环退出时释放计数器变量

c++ - 如何在不使用媒体转换管道的情况下在 Windows 应用程序中使用 MFT

C++ OpenGL 程序 - 添加图标

python - 可停止线程错误

c++ - Qt并发: call member function from another class

c# - 如何在计时器中使用异步和等待