我很新的C++和我现在正在尝试线程。 我想在while循环下的线程内创建一个线程。但我认为这似乎没有奏效。 目前我的代码看起来是这样的:在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套线程运行的原因。 让我知道如果有更快,更简单的方法来做到这一点?
它似乎等到内部线程完成,然后从下一次迭代开始。我想让内部线程在外部线程内同时运行。我可以知道如何解决这个问题吗?
打开你的编译器警告。你没有返回值。 – chris
你有[pthread_join](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html)*内循环...这就是为什么在等待。 – jsantander
'pthread_t threads [i];'你在第一次迭代中没有正确地分配('int i = 0;')。 –