use*_*525 1 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) ;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试读取一个文件,其中包含应该读取的文件列表。我想同时阅读所有这些文件。所有这些文件都包含信息,需要另一组线程来启动另一个操作。所以这也需要同时进行。这就是我运行 2 组线程的原因。让我知道是否有更快更简单的方法来做到这一点?
似乎要等到内线程完成,然后再开始下一次迭代。我希望内线程在外线程内同时运行。我可以知道该怎么做吗?
你对线程运行的看法是错误的。一个线程不在另一个线程内运行。它们是同一进程内的独立执行流,它们的共存是平面的,而不是分层的。
使用多线程时要遵循的一些简单规则:
在您的特定情况下,如果您想通过并行处理多个文件来加速处理它们(并假设这些线程需要完成的唯一任务是处理这些文件),那么可能的解决方案如下:
工作线程可以遍历它们的文件列表,一次读取一个并处理它们。
与您提出的解决方案相反,这个解决方案不会为每个文件创建一个线程。相反,它将创建尽可能多的线程可以在您的 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;
}
Run Code Online (Sandbox Code Playgroud)