【发布时间】:2014-08-03 01:37:08
【问题描述】:
我对 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 组线程的原因。 让我知道是否有更快更简单的方法来做到这一点?
似乎要等到内部线程完成,然后再开始下一次迭代。我希望内螺纹在外螺纹内同时运行。我可以知道该怎么做吗?
【问题讨论】:
-
打开编译器警告。你没有返回值。
-
你有pthread_join inside循环......这就是等待的原因。
-
pthread_t threads[i];在第一次迭代中,您没有正确分配此处 (int i = 0;)。 -
这里有很多问题。
pthread_t threads[i];在第一次迭代时大小为 0,&threads[i]指向数组末尾,j未在任何地方声明,等等。 -
... 线程 inside 线程这一事实没有意义。一个(重)进程包含一个或多个(轻)进程(又名线程)。这些线程是从代码中的不同点创建的,但执行线程创建请求的线程和生成的线程之间没有任何关系。
标签: c++ multithreading while-loop